尝试编写简单的python脚本,该脚本将使用NLTK查找和替换txt文件中的同义词。
以下代码给出错误:Traceback (most recent call last):
File "C:\Users\Nedim\Documents\sinon2.py", line 21, in
change(word)
File "C:\Users\Nedim\Documents\sinon2.py", line 4, in change
synonym = wn.synset(word + ".n.01").lemma_names
TypeError: can only concatenate list (not "str") to list
代码如下:from nltk.corpus import wordnet as wn
def change(word):
synonym = wn.synset(word + ".n.01").lemma_names
if word in synonym:
filename = open("C:/Users/tester/Desktop/test.txt").read()
writeSynonym = filename.replace(str(word), str(synonym[0]))
f = open("C:/Users/tester/Desktop/test.txt", 'w')
f.write(writeSynonym)
f.close()
f = open("C:/Users/tester/Desktop/test.txt")
lines = f.readlines()
for i in range(len(lines)):
word = lines[i].split()
change(word)