我读文本文件就像
awsm awesome
gr8 great
作为字典,我需要将缩写词替换为字典中正确的缩写词我使用了此代码,但它给了我错误“replace()参数2必须是str,而不是list”代码:
def acronym(text):
with open('acronym.txt') as fin:
rows= (line.split('\t') for line in fin )
d = { row[0]:row[1:] for row in rows }
acronym_words = []
words = word_tokenize(text)
for word in words:
for candidate_replacement in d:
if candidate_replacement in word:
word = word.replace(candidate_replacement, d[candidate_replacement])
acronym_words.append(word)
acronym_sentence = " ".join(acronym_words)
return acronym_sentence
acronym(" we are awsm and gr8") # to test function
在:
row[1:]
是一个产生列表的片。只需使用row[1]
,因为字典值应该是表示单个单词的字符串,而不是列表相关问题 更多 >
编程相关推荐