使用python将文本文件读取为字典,并使用此字典进行一些替换

2024-05-26 07:47:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我读文本文件就像

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

Tags: 代码textinfor字典awsmcandidatereplace
1条回答
网友
1楼 · 发布于 2024-05-26 07:47:14

在:

d = { row[0]:row[1:] for row in rows }

row[1:]是一个产生列表的片。只需使用row[1],因为字典值应该是表示单个单词的字符串,而不是列表

相关问题 更多 >