Skip to main content
 首页 » 编程设计

python之找到列表中的三个单词在给定文档中同时出现的频率

2024年11月01日8myhome

我在桌面上有多个 .txt 文件加载为 python 中的数据框。我在数据框中使用 python 工作,其中“文本”是我感兴趣的列的名称。 “文本”列由多个 .txt 文档组成。

我还有三个单词列表:它们是:

credit=['borrow', 'lend'], 
policy=['Fed', 'fund rate','zero'], 
trade=['deficit', 'surplus'], 

我的目标是构建一个索引,通过将其分别应用于每个文档来衡量文本文件中给定句子中三个列表中任何单词的组合频率。例如,如果 'borrow', 'fund' 和 'surplus' 在给定的句子中同时出现,它将enter code here 算作 1。

我知道如何使用单个单词进行计数,如下所示:

my_dir_path ='C:/Users/desktop' 
results = defaultdict(list) 
for file in Path(my_dir_path).iterdir(): 
    with open(file, "r") as file_open: 
        results["file_name"],(file.name) 
        results["text"].append(file_open.read()) 
        df = pd.DataFrame(results) 

为了获取单词 policy 跨文档的频率,我使用了以下代码:

df['policy']=df['text'].apply(lambda x: len([word for word in x.split() if     word=='policy'])) 

我怎样才能在 python 中做到这一点? 在此先感谢您的帮助?

请您参考如下方法:

我很想使用正则表达式来匹配句子中的单词,使用 lookahead/behind 我们可以使用类似的东西:

(?<!\w)borrow(?!\w) 

并且会在 "can I borrow that" 和 "will borrow." 中找到“borrow”,但不会在 “borrowing” 中找到“borrow”。我不确定你在这里到底想做什么,但我建议学习如何使用正则表达式,因为它们可以让你轻松表达这些选项

为了使下面的代码更短,我定义了一个函数来将一个“单词”编译成一个正则表达式对象:

import re 
 
def matcher(word): 
    return re.compile(fr'(?<!\w){word}(?!\w)', re.IGNORECASE) 
 
re_credit = [ 
    matcher('borrow'), 
    matcher('fund'), 
] 

接下来我编写了一个函数来将字符串拆分成句子,这样我们就可以计算单词的共现次数:

from nltk.tokenize import sent_tokenize 
 
def count_sentences_matching_words(text, regexes): 
    count = 0 
    for sentence in sent_tokenize(text): 
        if all(reg.search(sentence) for reg in regexes): 
            count += 1 
    return count 

接下来我们可以用一些文本来测试它:

para = "My goal is to construct the index that measures the frequency of any of the words from the three lists in combination in a given sentence in the text file by applying it for each document separately. For example if 'borrow', 'fund' and 'surplus' co-occurred in a given sentence, it willenter code here be counted as 1." 
 
count_sentences_matching_words(para, re_credit) 

如果你想将它与 pandas 一起使用,你可以做显而易见的事情:

df['credit'] = df['text'].apply(lambda x: count_sentences_matching_words(x, re_credit)) 

可能值得重新安排这段代码,例如每个文件只做一次句子标记化。但这取决于比你分享的更多的细节