简体   繁体   English

大文本文件:无法在python中将一个字符转换为另一个字符

[英]Large text file: Fails to convert one character into another in python

I'm pretty new to Python and want to convert one character into another character in a large string .txt file. 我是Python的新手,想将一个大字符串.txt文件中的一个字符转换为另一个字符。

I tried running the following code on shell: 我尝试在shell上运行以下代码:

#Takes text in letter and converts it
old_text = open("letter.txt", "r")

#Convert old_text to new_text replacing all instances of "a" or into "u"
new_text = old_text.upper().replace("a", "u")
print new_text

However, it returns the error "NameError: name 'old_text' is not defined" 但是,它返回错误“ NameError:未定义名称'old_text'”

Is there anything else I should do to fix this or am I missing something big here? 我还有什么其他方法可以解决此问题,或者我在这里错过了什么大事情?

First off, open() returns a file handle; 首先,open()返回文件句柄; you need to read the file from the handle if you want a string. 如果需要字符串,则需要从句柄中读取文件。

Then you're upper casing the whole string and searching for a lower case letter, which will never replace anything. 然后,将整个字符串用大写字母括起来,然后搜索一个小写字母,该字母将永远不会替换任何东西。

Unless there's part of your code that isn't here, it's unclear to me what's resulting in that error. 除非您的代码中没有一部分,否则我不清楚是什么导致了该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM