【发布时间】:2018-10-04 03:29:36
【问题描述】:
我有以下数据集:
import pandas as pd
jsonDF = pd.DataFrame({'DOCUMENT_ID':[263403828328665088,264142543883739136], 'MESSAGE':['@Zuora wants to help @Network4Good with Hurric...','@ztrip please help spread the good word on hel...']})
DOCUMENT_ID MESSAGE
0 263403828328665088 @Zuora wants to help @Network4Good with Hurric...
1 264142543883739136 @ztrip please help spread the good word on hel...
我正在尝试以
的形式重塑我的数据docID wordID count
0 1 118 1
1 1 285 1
2 1 1229 1
3 1 1688 1
4 1 2068 1
我用了以下
r=[]
for i in jsonDF['MESSAGE']:
for j in sortedValues(wordsplit(i)):
r.append(j)
IDCount_Re=pd.DataFrame(r)
IDCount_Re[:5]
给我以下结果
0 17
1 help 2
2 wants 1
3 hurricane 1
4 relief 1
5 text 1
6 sandy 1
7 donate 1
8 6
9 please 1
我可以统计字数
我不知道将 Document_ID 附加到上述数据框中。
以下函数用于拆分单词
from nltk.corpus import stopwords
import re
def wordsplit(wordlist):
j=wordlist
j=re.sub(r'\d+', '', j)
j=re.sub('RT', '',j)
j=re.sub('http', '', j)
j = re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", j)
j=j.lower()
j=j.strip()
if not j in stopwords.words('english'):
yield j
def wordSplitCount(wordlist):
'''merges a list into string, splits it, removes stop words and
then counts the occurrences returning an ordered dictitonary'''
#stopwords=set(stopwords.words('english'))
string1=''.join(list(itertools.chain(filter(None, wordlist))))
cnt=Counter()
j = []
for i in string1.split(" "):
i=re.sub(r'&', ' ', i.lower())
if i not in stopwords.words('english'):
cnt[i]+=1
return OrderedDict(cnt)
def sortedValues(wordlist):
'''creates a dictionary list of occurenced w/ values descending'''
d=wordSplitCount(wordlist)
return sorted(d.items(), key=lambda t: t[1], reverse=True)
更新:此处的解决方案:
【问题讨论】:
-
你可以将你的 i,j 循环和低效的追加组合到一个生成器表达式中:
wordcounts = Counter(word) for word in sortedValues(wordsplit(msg)) for msg in jsonDF['MESSAGE']) -
但这并不附加 DOCUMENT_ID,是吗?
-
我没这么说。我建议稍微清理一下您的代码。还有像合并你的正则表达式
re.sub(r'(\d+|RT|http)', '', j) -
您的
sortedValues()应替换为Counter().most_common()
标签: pandas nltk word-count