【问题标题】:Count the occurrences of a wordlist within a string observation计算字符串观察中单词列表的出现次数
【发布时间】:2022-01-11 13:09:34
【问题描述】:

我列出了学术文章摘要中出现频率最高的 10 个单词。我想计算这些词在我的数据集的观察中出现了多少次。

排名前 10 的单词是:

top10 = ['model','language','models','task', 'data', 'paper', 'results', 'information', 'text','performance']

前 3 个观察的示例是:

column[0:3] = ['The models are showing a great performance.',
'The information and therefor the data in the text are good enough to fulfill the task.',
'Data in this way results in the best information and thus performance'.]

提供的代码应返回特定观察中所有单词的总出现次数列表。我尝试了以下代码,但它给出了错误:count() 最多接受 3 个参数(给定 10 个)

我的代码:

count = 0
for sentence in column:
    for word in sentence.split():
        count += word.lower().count('model','language','models','task', 'data', 'paper', 'results', 'information', 'text','performance')

我还想将所有单词小写并删除标点符号。所以输出应该是这样的:

output = (2, 4, 4)

第一次观察统计top10列表中的2个词,即models和performance

第二次观察统计top10列表中的4个词,分别是信息、数据、文本和任务

第三次观察统计数据、结果、数据、信息和性能4个字

希望你能帮帮我!

【问题讨论】:

  • “提供的代码”在哪里,您遇到了什么错误/不正确之处?
  • 我已经更新了我的问题!

标签: python string find-occurrences multiple-occurrence


【解决方案1】:

您可以使用正则表达式进行拆分,然后检查它是否在前 10 位。

count =[]
for i,sentence in enumerate(column):
    c = 0
    for word in re.findall('\w+',sentence):
        c += int(word.lower() in top10)
    count += [c]

count = [2, 4, 4]

【讨论】:

  • 当我尝试这段代码时,我再次收到 [0, 0, 0] 的计数。除此之外,我的实际数据库大约有 10.000 个观察值。这是否意味着我应该为这 10.000 个观察值做一个 count =
  • @PaulEngelbert 我只使用您提到的 3 列。你应该调整它以适合你自己的代码,而不是不检查就复制
  • 我明白了,但是你知道一种方法来计算 10k 观察而不是一遍又一遍地复制 count = [0, 0, 0]?
  • @PaulEngelbert 很好,我刚改了
  • 成功了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 2013-02-01
相关资源
最近更新 更多