我有一个文本文件包含这样的内容:
Saya makan nasi padang semalam。Lauk yang aku pesan adalah ikan gurame。哈尔加尼亚玛哈尔。Aku juga makan dengan ayah dan ibuku。Setelah itu,Rina datang menemuiku。
我想在文本文件中找到特定的单词,然后打印包含特定单词的句子。我有很多具体的话。我尝试这样编码:
with open("kalimat.txt",'r') as f:
text = f.read()
# f.close()
words = ["makan","Rina","mahal"]
for item in text.split("\n"):
if words in item:
print(item.strip())
Run Code Online (Sandbox Code Playgroud)
我收到错误TypeError: 'in ' 需要字符串作为左操作数,而不是列表。 如何打印包含许多特定单词的句子?
小智 5
def my_function():
with open("exampleValues",'r') as f, open('output.txt','w') as fw:
text = f.read()
result_string = ''
words = ["makan", "Rina", "mahal"]
text2 = text.split(".")
for itemIndex in range(len(text2)):
for word in words:
if word in text2[itemIndex]:
if text2[itemIndex][0] ==' ':
print(text2[itemIndex][1:])
result_string += text2[itemIndex][1:]+'. '
break
else:
print(text2[itemIndex])
result_string += text2[itemIndex]
break
print(result_string)
fw.write(result_string)
my_function()
Run Code Online (Sandbox Code Playgroud)
如果这个有用的话。别忘了给我投票。谢谢。
| 归档时间: |
|
| 查看次数: |
13154 次 |
| 最近记录: |