我有来自不同来源的大量名字。
所以我想提取一个按人气排序的短语列表。
以下是名称的示例:
Post Office - High Littleton
Post Office Pilton Outreach Services
Town Street Post Office
post office St Thomas
基本上需要找出一些算法或更好的库,才能得到这样的结果:
Post Office: 16999
Post: 17934
Office: 16999
Tesco: 7300
...
以下是完整的example of names。
我写的代码对单个单词很好,但不适用于句子:
from textblob import TextBlob
import operator
title_file = open("names.txt", 'r')
blob = TextBlob(title_file.read())
list = sorted(blob.word_counts.items(), key=operator.itemgetter(1))
print list
答案 0 :(得分:0)
你不是在寻找聚类(这可能就是为什么"所有这些都很糟糕"对于@andrewmatte而言)。
您正在寻找的是字数统计(或更确切地说,n-gram-counting)。这实际上是一个更容易的问题。这就是为什么你不能找到任何库...
嗯,实际上你是一些图书馆。例如,在python中,collections
模块具有类Counter
,其中包含大量可重用代码。
未经测试的非常基本的代码:
from collections import Counter
counter = Counter()
for s in sentences:
words = s.split(" ")
for i in range(len(words)):
counter.add(words[i])
if i > 0: counter.add((words[i-1], words[i]))
你从counter
得到的频率最高。如果您想要单词和单词对分开,请随意使用两个计数器。如果您需要更长的短语,请添加内循环。您可能还想要清除句子(例如小写)并使用正则表达式进行拆分。
答案 1 :(得分:0)
你在找这样的东西吗?
workspace={}
with open('names.txt','r') as f:
for name in f:
if len(name): # makes sure line isnt empty
if name in workspace:
workspace[name]+=1
else:
workspace[name]=1
for name in workspace:
print "{}: {}".format(name,workspace[name])