【问题标题】:How to count how many times a word appears in a column, python如何计算一个单词在一列中出现的次数,python
【发布时间】:2017-09-15 03:52:37
【问题描述】:

如何用 Python 计算一个单词在某个列的字符串中出现的次数?例如:

file|context
----|-------
1   | Hello world
2   | Round and round

我要计算单词的出现次数:

file| context         | word_count
----|-----------------|---------------------
1   | Hello world     | {'hello':1,'world':1}
2   | Round and round | {'round':2,'and':1}

我已经坚持了一整天,并尝试使用 value_counts() 和 Counter。还是想不通。有什么帮助吗?

谢谢!

【问题讨论】:

  • 您是如何尝试使用 Counter 和 value_counts() 的?
  • 你展示了什么样的数据结构?如果您正在讨论解析文本表与处理 pandas 数据框之类的东西,您会得到非常不同的答案。添加适当的标签,也许(stringcount 在这里毫无用处)。

标签: python string count


【解决方案1】:

您可以在拆分字符串的小写版本上使用collections.Counter

from collections import Counter

s = 'Round and round'
counts = Counter(s.lower().split())
print(dict(counts))

输出:

{'和':1,'圆形':2}

接下来,您需要对其进行调整以处理您的数据。数据格式似乎使用了固定宽度的字段,因此上下文列从位置 7 开始。假设数据来自文件:

with open('data') as f:
    next(f)    # skip the header
    next(f)    # skip the border
    # print new header and border

    for line in f:
        counts = Counter(line[6:].lower().split())
        print('{} | {}'.format(line, dict(counts)))

需要做一些工作才能将计数正确格式化到输出列中。

【讨论】:

  • 感谢您提供的信息。帮了大忙!
【解决方案2】:

您可以为此使用 python in-build 函数Counter

In [5]: from collections import Counter

In [6]: string = 'Hello world'

In [9]: count = Counter(string.lower().split())

In [10]: print(dict(count))
{'world': 1, 'hello': 1}

将单词转换为lowercase,因为Counter 以不同的方式考虑大写和小写。

【讨论】:

  • 感谢您的帮助!
【解决方案3】:

以下是单词在字符串中出现的次数

str = "Round and round"
dict1={}
for eachStr in str.split():
    if eachStr.lower() in dict1.keys():
        count = dict1[eachStr]
        count = count + 1
        dict1[eachStr.lower()] = count
    else:
        dict1[eachStr.lower()] = 1
print dict1

输出:

{'and': 1, 'round': 2}

【讨论】:

    猜你喜欢
    • 2016-01-09
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2012-01-06
    • 1970-01-01
    • 2011-06-20
    相关资源
    最近更新 更多