Python:从字典中替换文本文件中的多个单词
我无法弄清楚我哪里出错了.因此,我需要随机替换单词并将其重新写入文本文件,直到对其他人不再有意义.我选择了一些单词来测试它,并编写了以下代码,目前无法正常工作:
# A program to read a file and replace words until it is no longer understandable word_replacement = {'Python':'Silly Snake','programming':'snake charming','system':'table','systems':'tables','language':'spell','languages':'spells','code':'snake','interpreter':'charmer'} main = open("INF108.txt",'r+') words = main.read().split() main.close() for x in word_replacement: for y in words: if word_replacement[x][0]==y: y==x[1] text = " ".join(words) print text new_main = open("INF108.txt",'w') new_main.write(text) new_main.close() 这是文件中的文字:
我已经尝试了一些方法,但作为Python的新手,这是一个猜测的问题,并且最近两天花在网上进行研究,但我发现的大部分答案要么太复杂,我不能理解,或是特定于该人的代码,并没有帮助我. 解决方法
好的,让我们一步一步来.
main = open("INF108.txt",'r+') words = main.read().split() main.close() 最好在这里使用 with open("INF108.txt") as main: words = main.read().split() 使用with将使main.close()在此块结束时自动为您调用;你也应该为最后的文件写做同样的事情. 现在为主要位: for x in word_replacement: for y in words: if word_replacement[x][0]==y: y==x[1] 这个小部分包含了几个误解: >迭代字典(对于word_replacement中的x)仅为您提供密钥.因此,当您想稍后进行比较时,您应该检查word_replacement [x] == y.在那上面做[0]只会给你替换的第一个字母. 你想要做的是创建一个可能被替换的单词的新列表,如下所示: replaced = [] for y in words: if y in word_replacement: replaced.append(word_replacement[y]) else: replaced.append(y) text = ' '.join(replaced) 现在让我们做一些改进.字典有一个方便的 replaced = [] for y in words: replacement = word_replacement.get(y,y) replaced.append(replacement) text = ' '.join(replaced) 您可以将其转变为单行list-comprehension: text = ' '.join(word_replacement.get(y,y) for y in words) 现在我们已经完成了. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |