在文本文件中查找特定单词并使用Python打印该行

时间:2018-07-28 02:01:42

标签: python

我有一个文本文件包含如下内容:

  

Saya makan nasi padang semalam。 Lauk yang aku pesan adalah ikan gurame。 Harganya mahal。 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())

我收到错误 TypeError:'in'要求将字符串作为左操作数,而不是列表。 如何打印包含许多特定单词的句子?

6 个答案:

答案 0 :(得分:1)

由于要打印句子,因此应使用“。”分隔段落。

sentences = text.split('.')
for sentence in sentences :
     for word in words :
           if word in sentence :
                print (sentence)

答案 1 :(得分:1)

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()

如果有用。别忘了给我投票。谢谢。

答案 2 :(得分:0)

def my_function():

  with open("exampleValues",'r') as f:
      text = f.read()
      words = ["makan", "Rina", "mahal"]
      text2 = text.split("\n")
      for itemIndex in range(len(text2)):
          if words[0] in text2[itemIndex] or words[1] in text2[itemIndex] or 
words[2] in text2[itemIndex]:
                  print(text2[itemIndex].strip())
my_function()

我发现如果使用Samraj Moorjani的逻辑,如果我们尝试将两个或三个单词放在同一行中,则该行将被输出2或3次。希望我的代码有用。

答案 3 :(得分:0)

def my_function():

  with open("exampleValues",'r') as f:
      text = f.read()
      words = ["makan", "Rina", "mahal"]
      text2 = text.split("\n")
      for itemIndex in range(len(text2)):
          for word in words:
              if word in text2[itemIndex]:
                  print(text2[itemIndex])
                  break
my_function()

此答案将比我上面的答案更有用。谢谢阿尔维特。

答案 4 :(得分:0)

您还可以使用集合:

with open("kalimat.txt",'r') as f:
    text = f.read()

search_words = set(["makan","Rina","mahal"])

for sentence in text.split("."):
    words_in_sentence = set(sentence.split())
    if words_in_sentence.intersection(search_words):
        print(sentence)

答案 5 :(得分:-1)

您无法在字符串中搜索列表。您需要在字符串中寻找一个字符串。使用索引符号搜索列表中的每个项目。

for item in text.split("."):
    for index in range (0,len(words)):
        if words[index] in item:
            print(item.strip())

您可以从那里拿走它,并确保通过跳出循环在单个句子中考虑多个单词。

修改

将“ \ n”更改为“。”

相关问题