[英]Find phrases from one text file in another text file with python
我有一個文件是短語列表,每行一個短語。 另一個文件沒有任何定界,只是一個巨大的單詞文本文件。 我想在第二個文件中搜索短語,如果找到它們,則打印該短語。 這是我到目前為止的代碼。
f = open("phrase.txt", "r")
g = open("text.txt", "r")
for line in f:
search=line.lower()
for word in g:
if search in word:
print(search)
不過,這並沒有為我打印任何內容。
編輯:我將代碼更改為此:
f = open('phrase.txt').readlines()
f = [f.strip('\n').lower() for f in f]
g = open('text.txt').read()
for phrase in f:
if phrase in g:
print (phrase)
現在我得到了匹配的短語。 但是,某些詞組后面帶有破折號(-)和更多字母,即使text.txt中包含破折號之前的短語,程序也不會選擇它們。 有什么辦法改變嗎?
如果要搜索文件中的每個短語,則必須嵌套循環,當前,您只是在搜索最后一個短語
phrases = open("phrase.txt").readLines()
for phrase in phrases:
search= phrase.lower()
words = open("text.txt", "r")
for word in words:
if search in word:
print(search)
words.close()
但是,現在事情開始看起來很有趣,因為您要問一個詞是否在單詞中,這似乎不太對勁。 所以
phrases = open("phrase.txt").readLines()
words = open("text.txt").read()
for phrase in phrases:
all_words_found = True
phrase_words = phrase.lower().split(" ")
for word in phrase_words:
if word not in words:
all_words_found = False
break
if all_words_found:
print phrase
這就是我想要的
f = open('phrase.txt').readlines()
f = [f.strip('\n').lower() for f in f]
g = open('text.txt').read()
words = g.split()
for phrase in f:
search_words = phrase.split()
for word in search_words:
if word in words:
print phrase
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.