Hat*_*cia 3 python dictionary replace text-files python-2.7
我无法弄清楚我哪里出错了.因此,我需要随机替换单词并将其重新写入文本文件,直到对其他人不再有意义.我选择了一些单词来测试它,并编写了以下代码,目前无法正常工作:
# 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()
Run Code Online (Sandbox Code Playgroud)
这是文件中的文字:
Python是一种广泛使用的通用高级编程语言.它的设计理念强调代码可读性,其语法允许程序员用比C++或Java等语言更少的代码行表达概念.该语言提供了用于在小规模和大规模上实现清晰程序的构造.Python支持多种编程范例,包括面向对象,命令式和函数式编程或程序样式.它具有动态类型系统和自动内存管理功能,并具有大型全面的标准库.Python解释器可在许多操作系统上安装,允许在各种系统上执行Python代码.使用第三方工具,如Py2exe或Pyinstaller,可以将Python代码打包到一些最流行的操作系统的独立可执行程序中,允许分发基于Python的软件,以便在这些环境中使用而无需安装一个Python解释器.
我已经尝试了一些方法,但作为Python的新手,这是一个猜测的问题,并且最近两天花在网上进行研究,但我发现的大部分答案要么太复杂,我不能理解,或是特定于该人的代码,并没有帮助我.
好的,让我们一步一步来.
main = open("INF108.txt", 'r+')
words = main.read().split()
main.close()
Run Code Online (Sandbox Code Playgroud)
最好在with这里使用声明.此外,r是默认模式.从而:
with open("INF108.txt") as main:
words = main.read().split()
Run Code Online (Sandbox Code Playgroud)
使用with将main.close()在此块结束时自动为您调用; 你也应该为最后的文件写做同样的事情.
现在为主要位:
for x in word_replacement:
for y in words:
if word_replacement[x][0]==y:
y==x[1]
Run Code Online (Sandbox Code Playgroud)
这个小部分包含了几个误解:
for x in word_replacement)仅为您提供密钥.因此,当您想稍后进行比较时,您应该进行检查if word_replacement[x] == y.做一个[0]只是给你替换的第一个字母.y in word_replacement.y == x[1]两种方式都是错误的.首先,你可能意味着要分配到y那里,而不是比较(即y = x[1]- 注意单个=符号).其次,分配给循环变量甚至不能做你想要的.y下次循环时会被新值覆盖,words数据根本不会改变.你想要做的是创建一个可能被替换的单词的新列表,如下所示:
replaced = []
for y in words:
if y in word_replacement:
replaced.append(word_replacement[y])
else:
replaced.append(y)
text = ' '.join(replaced)
Run Code Online (Sandbox Code Playgroud)
现在让我们做一些改进.字典有一个方便的get方法,可以让你在键存在时获得一个值,如果不存在则可以获得默认值.如果我们只使用单词本身作为默认值,我们会得到一个漂亮的减少:
replaced = []
for y in words:
replacement = word_replacement.get(y, y)
replaced.append(replacement)
text = ' '.join(replaced)
Run Code Online (Sandbox Code Playgroud)
您可以将其转变为单行列表理解:
text = ' '.join(word_replacement.get(y, y) for y in words)
Run Code Online (Sandbox Code Playgroud)
现在我们已经完成了.
| 归档时间: |
|
| 查看次数: |
3301 次 |
| 最近记录: |