使用Python查找包含关键字数组之一的句子

2024-05-13 06:03:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.7

我想浏览一个.txt文件,只保留包含一个或多个关键字列表的句子。在

在那之后,我想用另一个关键字列表再次检查剩余的文本并重复这个过程。在

结果我想保存在那个.txt中,剩下的可以删除。在

我是Python的新手(但我很喜欢它!)所以别担心会伤害我的感情,你可以自由地假设我的知识不多,然后再把它哑一点:)

到目前为止,我得到的是:

import re

f = open('C:\\Python27\\test\\A.txt')

text = f.read()
define_words = 'contractual'
print re.findall(r"([^.]*?%s[^.]*\.)" % define_words,text)

到目前为止,它可以过滤掉任何带有“契约”的句子。如果我把‘契约义务’放在那里,它会过滤掉那些两个词相邻的句子。在

我的问题是如何把它变成一组词,这些词会被分开来考虑?如“合同”、“义务”、“法律”、“雇主”等

编辑applepi的回答:

我用一个小测试做了一些测试:

“敏捷的棕色狐狸跳过懒狗。在

新线。在

又是一条不错的新线。”

我只得到一个句子,如果我把两个单词放在这个句子的字符串中。比如['quick'、'brown']

输出:['T','h','e','''q','u','i','c','k','''b','r','o','w','n',''f','o','x','y','''j','u','m','p','s',''o','r','''T','h','e','''l','a','z','y','''d','o','g','.']

所以,['快','另一个']什么都没有。在

['Yet','another']将提出:

输出:[','\n','\n','Y','e','t',''a','n','o','t','h','e','r',''n','e','w',''l','i','n','e','.']


Tags: 文件text文本retxt列表过程关键字
3条回答

为什么不使用列表理解?在

print [sent for sent in text.split('.') 
        if any(word in sent for word in define_words.split()) ]

或者,如果更改字符串列表的define_words:

^{pr2}$

我不能评论(我没有足够的声誉),所以这个答案在技术上不是一个答案。在

我不太熟悉regex,但是假设您的re.findall()成功,您可以使用以下代码:

import re, itertools
from collections import Counter
f = open('C:\\Python27\\test\\A.txt')

text = f.read()
everything = []
define_words = ['contractual', 'obligation', 'law', 'employer']
for k in define_words:
    everything.append(re.findall(r"([^.]*?%s[^.]*\.)" % k,text))

everything = list(itertools.chain(*everything))
counts = Counter(everything)
everything = [value for value, count in counts.items() if count > 1]
everything = list(itertools.chain(*everything))
print everything

这将循环遍历数组列表并将值添加到列表中,从而生成列表列表。然后我只保留重复项(好值),并将列表列表转换为一个列表。在

错误:真正的错误是所有东西都是一个列表列表,Counter(everything)不允许这样做。因此,我在Counter()之前将其剥离。在

def init_contains_useful_word(words_to_search_for):

    def contains_useful_word(sentence):
        return any(map(lambda x: x in sentence, words_to_search_for))

with open(filename, 'r') as f:
    text = f.read()

sentences = text.split(".")

for words in list_of_lists:
    contains_useful_word = init_contains_useful_word(words)

    sentences = filter(contains_useful_word, sentences)

with open(filename, 'w') as f:
    f.write(sentences.join(" "))

实际上,如果你愿意,你可以用你的重运算符替换包含有用的单词。在

相关问题 更多 >