![](/img/trans.png)
[英]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.