-6

我有一个包含单词的文件,我想读取这个文件并在所有单词前面添加一个标签。标签应加在单词的右侧。例如。book - "O", Berlin - "O". 如何在python中做到这一点?我已经尝试过这段代码,但没有给出我的答案。

inp = open('Dari.pos', 'r')
out = open('DariNER.txt', 'w')

for line in iter(inp):
    word= line.__add__("O")
    out.write(word)
inp.close()
out.close()
4

2 回答 2

0

如果我理解正确的输出格式 word-O,你可以尝试这样的事情:

words = open('filename').read().split()
labeled_words = [word+"-O" for word in words]

# And now user your output format, each word a line, separate by tabs, whatever.
# For example new lines
with open('outputfile','w') as output:
    output.write("\n".join(labeled_words))
于 2018-02-06T14:33:36.917 回答
0

在您更新的问题中,您显示了添加了一些字符的单词示例(我假设您的意思是行):

eg. book - "O", Berlin - "O"

对代码的这种修改应该会产生该输出:

for line in iter(inp):
    word = '{} - "O"'.format(line)
    out.write(word)

我用下面的代码进行了测试:

inp = ['This is a book','I bought it in Berlin']

for line in iter(inp):
    word = '{} - "O"'.format(line)
    print(word)

输出:

This is a book - "O"
I bought it in Berlin - "O"
于 2018-02-06T14:48:11.787 回答