[英]How to read a text file and write it word by word into another file in python?
[英]How to read a word/string from a text file in python?
意味着我想阅读所有包含相同单词或句子的行,然后在 python 3 中打印它们
请帮助我用一种简单的方法来做到这一点。
这可以使用 Python 的基本功能和for
循环来完成。
这是一个使用随机句子的示例,例如:
“你好,世界再见。我很高兴见到你。你好,世界,你好吗。”
假设句子包含在文件中,即 file.txt。 使用open()
您可以读取 your.txt 文件。 然后只需遍历每个字符串并打印包含您需要的单词的行:
with open("file.txt") as f:
for i in f:
for j in i.split():
if j == "world":
print(i)
Output:
Hello world good bye world.
Hola world how are you.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.