如何解决读取文本文件进行格式化
我希望程序使用Python读取并打印txt文件中的短语。我希望程序在txt文件中设置的逗号数后输出该短语。在下面查看所需的输出以查看示例。
文本文件包含:
Hello,I am a bird,a tree,an elephant,a leopard,perhaps a non living object,what am I?
Python代码的预期输出:
After what comma do you want the code to print: 0
Phrase is: Hello
After what comma do you want the code to print: 1
Phrase is: I am a bird
After what comma do you want the code to print: 4
Phrase is: perhaps a non living object
解决方法
使用read()将文件读取为字符串,然后使用join()解析为列表。
with open("file.txt",'r') as f:
data = f.read()
parsed_data = ",".join(data)
,
我想这就是你要的:
import re
# data = "Hello,I am a bird,a tree,an elephant,a leopard,perhaps a non living object,what am I?"
with open('/tmp/data.txt') as f:
data = f.readline()
parts = re.split(r",\s+",data)
while True:
w = input("After what comma do you want the code to print: ")
if not w:
break
print('Phrase is: ' + parts[int(w)])
样品运行:
After what comma do you want the code to print: 0
Phrase is: Hello
After what comma do you want the code to print: 3
Phrase is: an elephant
After what comma do you want the code to print: 2
Phrase is: a tree
After what comma do you want the code to print: 1
Phrase is: I am a bird
After what comma do you want the code to print:
Process finished with exit code 0
,
只需将文件中的文本视为字符串,然后使用split方法。它将为您提供每个细分的数组。参见示例:
>>> 'Hello,what am I?'.split(',')
[“你好”,“我是鸟”,“树”,“大象”,“豹”,“也许是非生物物体”,“我是什么?”
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。