![](/img/trans.png)
[英]In Python, how do I parse each word in a text file and make each word lowercase and remove special characters except for apostrophes?
[英]How do I import lines from a text file without format characters (backslashes/apostrophes) in Python3
第一篇文章和新手编码。 抱歉,如果这是多余的。 我搜索了高低,还没有遇到特定于这个特定问题的东西。
我正在使用 Python3 设计一个选择你自己的冒险游戏。 文本有点重,所以我想将对话和其他故事方面保存在一个单独的文本文件中,这样我就可以使我的代码尽可能精简和干净。 我尝试了一些不同的策略,但都没有成功,包括尝试在文本文件中实现字典以在脚本中使用,如索引。 我并没有贬低这种策略,而是继续前进,这就是我目前所处的位置:
def intro():
intro = open("try.txt", "r")
print(intro.readlines(0))
intro()
其中 0 是文本文件中的第一行文本。 我希望在通过提示导航脚本时,我可以在 select 各个行中抓取和显示,但是 output 在文本的主体周围包含方括号,并且在撇号之前包含反斜杠。 例如:['公海的紧张局势正在加剧。 有麻烦了。']
有什么方法可以防止使用这种方法在打印的 output 中添加转义字符和/或方括号?
提前致谢!
您看到的转义字符不是来自文件。 当您调用readlines()
时,您会得到一个字符串列表:
>>> f = open("foo.txt", 'r')
>>> f.readlines()
['hello world!\n', 'hello world!\n', 'hello world!\n', 'hello world!\n', 'hello world!\n', 'hello world!\n', 'hello world!\n', 'hello world!\n', 'hello world!\n', 'hello world!\n']
这就是 function 在您调用它时返回的内容。 然后你在列表上调用repr()
,它主要用于将对象显示为结构化的类似代码的文本 - 而不是将它们显示为常规字符串。 它在错误消息中很有用,或者记录 output 等等。
要在调用getlines()
后从文件中获取单行文本 - 它将所有行作为列表返回,您可以像任何其他列表一样对其进行索引:
print(myfile.getlines()[0])
以这种方式使用print(...)
^,您可以获得没有任何额外字符的行内容。
print(repr(myfile.getlines()[0]))
并且,以这种方式使用print(...)
^,将显示引号和转义换行符等:
所以这里没有发生文件文本编解码器的奇怪现象。 这就是它应该如何工作的方式。
readlines
从文件中读取所有行并返回一个数组,其中每一行都有一个元素。 它的参数是size_hint
,表示可能的行长; 它不指示要读取哪一行。 如果要按索引访问特定元素,则必须使用方括号[0]
。
repr
用于获取 object 的字符串表示形式。 由于您正在使用字符串,因此没有必要因为字符串的表示本身就在引号内。
您最需要的是:
def intro():
intro = open("try.txt", "r")
print(intro.readlines()[0])
intro()
当您执行 print(repr(intro.readlines(0))) 时,您正在打印整个字符串列表,而不仅仅是其中一个字符串。 这就是为什么您会在要打印的字符串周围看到括号和引号。 我会尝试这样的事情
def intro():
intro = open("try.txt", "r")
line_list = intro.readlines()
print(line_list[0])
intro()
对于撇号前面的反斜杠,您可以处理 line_list 中的每个字符串以尝试将其删除。 我不完全确定你为什么会看到那些反斜杠。
def intro():
intro = open("try.txt", "r")
line_list = intro.readlines()
new_line_list = []
for line in line_list:
new_line_list.append(line.replace("\\", ""))
print(new_line_list[0])
intro()
def intro():
intro = open("try.txt", "r")
print(intro.readlines()[0]) # here
intro()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.