[英]How to read a word/string from a text file in python?
Means I wanted to read all the line which contains the same word or a sentence and then print them in python 3意味着我想阅读所有包含相同单词或句子的行,然后在 python 3 中打印它们
Please help me with a easy way to do so.请帮助我用一种简单的方法来做到这一点。
This can be done using the basic functions of Python and a for
loop.这可以使用 Python 的基本功能和
for
循环来完成。
Here is an example using random sentences for example:这是一个使用随机句子的示例,例如:
"Hello world good bye world. I am happy to see you. Hola world how are you." “你好,世界再见。我很高兴见到你。你好,世界,你好吗。”
Let's say the sentences are contained in a file as file.txt.假设句子包含在文件中,即 file.txt。 Using
open()
you can read your.txt file.使用
open()
您可以读取 your.txt 文件。 Then just iterate over each string and print the line containing the word you need:然后只需遍历每个字符串并打印包含您需要的单词的行:
with open("file.txt") as f:
for i in f:
for j in i.split():
if j == "world":
print(i)
Output: Output:
Hello world good bye world.
Hola world how are you.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.