2017-09-15 309 views
0

如何計算一個單詞在一列中的字符串出現在Python中的次數?例如:如何計算單詞在一列中出現的次數,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()和計數器。仍然無法弄清楚。任何幫助?

謝謝!

+0

你是如何嘗試使用Counter和value_counts()? –

+0

你正在展示什麼樣的數據結構?如果您正在討論解析文本表而不是像pandas'數據框這樣的工作,你會得到非常不同的答案。可能會添加適當的標籤('string'和'count'在這裏非常無用)。 – Blckknght

回答

2

您可以在分割字符串的小寫版本使用collections.Counter

from collections import Counter 

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

輸出:

 
{'and': 1, 'round': 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))) 

還有一些工作要做計數正確格式化爲輸出列。

+0

感謝您的信息。它幫助了很多! – Lily

0

下面給出了一個字次的數的計數出現在字符串

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 

OUTPUT:

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

您可以使用Python中,構建功能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大寫和小寫的不同。

+1

謝謝你的幫助! – Lily

相關問題