- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我需要计算语料库中单词的出现频率。通常我使用 collections 包中的 Counter 类。
from collections import Counter
list_of_words = ['one', 'two', 'three', 'three']
freqs = Counter(list_of_words)
但是,我正在分析的语料库由几百万个单词组成,所以如果有更快的方法来计算这些分数会很好吗?
下面是读入单词的代码:
from read_cg3 import read_cg3
test = read_cg3('/Users/arashsaidi/Work/Corpus/DUO_Corpus/Bokmaal-tagged-random/DUO_BM_0.txt')
count = 0
word_list = []
for sentence in test:
for word in sentence:
count += 1
word_list.append(word)
print count
read_cg3 是一个读取已解析文件并返回句子列表的模块。这是模块:
import re
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def read_cg3(cg3_file):
"""
Reads a cg3 file and returns a list of each sentence with Token, parsed, and one tag
:param cg3_file: path to file
:return: list of words + attributes
"""
rx_token = re.compile("^\"<(.+?)>\"$")
rx_attributes = re.compile("^\s+\".+?\"\s+.+$")
rx_eos = re.compile("^\s*$")
curr_token = None
curr_word = []
curr_sentence = []
result = []
with open(cg3_file) as cg3_file:
for line in cg3_file:
if rx_token.match(line):
curr_token = "\"%s\"" % rx_token.match(line).group(1)
# print curr_token
if rx_attributes.match(line):
curr_word = line.split()
# print curr_word[0], curr_word[1]
# print curr_word
if curr_token and curr_word:
# to get more tags uncomment this and comment below
# curr_sentence += [[curr_token] + curr_word]
if '$' not in curr_word[0] and not is_number(curr_word[0].strip('"').replace('.', '')) \
and len(curr_word[0]) < 30:
# curr_sentence += [[curr_token.strip('"')] +
# [curr_word[0].lower().strip('"')] + [curr_word[1]]]
curr_sentence += [curr_word[0].lower().strip('"')]
curr_token = None
curr_word = []
if rx_eos.match(line):
# print curr_sentence
if curr_sentence:
result += [curr_sentence]
curr_sentence = []
curr_token = None
curr_word = []
# cleanup if last sentence not EOL
if curr_token and curr_word:
print 'cg3 reached end of file and did some cleanup on file {}'.format(cg3_file)
curr_sentence += [[curr_token] + curr_word]
if curr_sentence:
print 'cg3 reached end of file and did some cleanup on file {}'.format(cg3_file)
result += curr_sentence
return result
这是 read_cg3 读取文件的方式:
"<TEKNOLOGI>"
"teknologi" subst appell mask ub ent
"<OG>"
"og" konj <*>
"<UNDERVISNING>"
"undervisning" subst appell fem ub ent <*>
"<|>"
"$|" clb <overskrift> <<<
"<En>"
"en" det mask ent kvant
"<intervjuunders¯kelse>"
"intervjuunders¯kelse" subst appell mask ub ent
"<av>"
"av" prep
"<musikklÊreres>"
"musikklÊrer" subst appell mask ub fl gen
"<didaktiske>"
"didaktisk" adj fl pos
"<bruk>"
"bruk" subst appell mask ub ent
"<av>"
"av" prep
"<digitale>"
"digital" adj fl pos
"<verkt¯y>"
"verkt¯y" subst appell n¯yt ub fl <*¯y>
"<i>"
"i" prep
"<undervisningsfaget>"
"undervisningsfag" subst appell n¯yt be ent
"<komposisjon>"
"komposisjon" subst appell mask ub ent
"<i>"
"i" prep
"<videregÂende>"
"videregÂende" adj ub m/f ent pos
"<skole>"
"skole" subst appell mask ub ent
"<|>"
"$|" clb <overskrift> <<<
"<Markus>"
"Markus" subst prop mask
"<A.>"
"A." subst prop fork <*>
"<SkjÊrstad>"
"SkjÊrstad" subst prop <*stad> <*>
"<|>"
"$|" clb <overskrift> <<<
我的方法只读入一个文件,这是为了测试,语料库由大约30000个文件组成。
最佳答案
看起来您不需要使用标记,并且您的正则表达式可以取消。这将计算每个单词在每个文件中出现的次数:
import multiprocessing as mp
import os
import itertools
def wordCounter(qIn, qOut):
answer = {}
for fname, words in iter(qIn.get, None):
for word in words:
if fname not in answer:
answer[fname] = {}
if word not in answer[fname]:
answer[fname][word] = 0
answer[fname][word] += 1
qOut.put(answer)
def getLines(corpusPath, qIn, numProcs):
for fname in os.listdir(corpusPath):
with open(os.path.join(corpusPath, fname)) as infile:
for i, (k,lines) in enumerate(itertools.groupby((l.strip() for l in infile), lambda line : bool(line) and not line.startswith('"<') and "$" not in line.split(None,1)[0])):
if not k:
continue
qIn.put((fname, [line.split(None,1)[0].strip('"').strip().lower() for line in lines]))
for _ in range(numProcs):
qIn.put(None)
def main(corpusPath):
qIn, qOut = [mp.Queue() for _ in range(2)]
procs = [mp.Process(target=wordCounter, args=(qIn, qOut)) for _ in range(mp.cpu_count() -1)]
lineGetter = mp.Process(target=getLines, args=(corpusPath, qIn, len(procs)))
lineGetter.start()
for p in procs:
p.start()
answer = {}
for _ in range(len(procs)):
for fname, wdict in qOut.get().items():
if fname not in answer:
answer[fname] = {}
for word,count in wdict.items():
if word not in answer[fname]:
answer[fname][word] = 0
answer[fname][word] += count
for fname in sorted(answer):
for word in sorted(answer[fname]):
print("{} appeared in {} {} times".format(word, fname, answer[fname][word]))
for p in procs:
p.terminate()
lineGetter.terminate()
整个过程只用了不到一秒钟的时间来处理您的测试文件。请注意,其中一些是由于设置子进程的开销造成的,因此这应该可以更好地扩展到大型语料库。
希望对你有帮助
关于python - 在 Python 中快速计算频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27649310/
我有一个包含 34 个变量和大约 25,000 个观测值的数据集。每个观察都涉及一个特定事件。它的格式如下: no id date .... 1 363 006
我已将 R 连接到 Twitter 并使用 R 中的 searchTwitter 函数进行抓取,并清除标点符号、小写字母等结果数据。现在我正在尝试执行以下操作: 计算自 2015 年 1 月 至 20
我正在研究项目,需要可视化频谱分析以设置一些精确参数。现在,我将垃圾箱转换为屏幕空间,因为在线性空间中,较低频率的幅度被压缩在一起。这是我在C++中的代码: float windowSize = 64
我正在尝试使用MATLAB导入WAV文件并创建如下所示的图表类型。我基本上是在尝试获取频率信息并根据分贝对其进行绘制。这是我正在使用的代码,但似乎无法正确提取频率信息: [x fs]=wavread(
我有一个 GUI,可以计算字符串中第一个字母的出现次数。我希望它以列格式计算所有字母,例如: 这是我到目前为止所拥有的: import java.awt.BorderLayout; import ja
我有一个由许多变量组成的全国调查,就像这个(为了简单起见,我省略了一些变量): year id y.b sex income married pens weight 2002
我被要求报告我们客户的联系频率,即每周、每月、每季度或每年看到多少客户。 当在论坛中讨论“频率”时,它们通常是指某个值在表中存在的次数。 我可以获得客户的联系人数量:- select A.cl
我正在尝试制作一款游戏,当麦克风发出足够响亮的声音时,我的角色会射击(在 Unity 中)。但是我不知道如何开始。 感谢您的帮助! 最佳答案 您可以通过使用 AudioSource.GetOutput
尝试计算字符数并改进我的代码,我做了一些更改,而不是使用 while 循环。好奇是否有人对我如何改进我的代码以使其更专业且更便宜有任何建议? #include int countingCharact
我正在创建一个 MySQL 数据库,其中包含大量带有时间戳的条目。这些条目将附加到特定用户和另一个索引(例如博客作者和他的几个网站)。计算用户/全局每日条目图表的最佳方法是什么。 我的两种方法是使用
我创建了一项调查并将其发送出去。该调查要求用户提供电子邮件,然后要求他们从包含 8 个不同选项的下拉菜单中选择要吃哪顿饭。有些人使用同一封电子邮件多次填写调查,但食物选择不同。 我有一个如下所示的 M
我有一个 MySQL 数据库: Date Customer_ID 我怎样才能把它变成: Customer_ID | Count_Visits_Past_Week | Count_Visits_
对于非常大的数据集,如何使用 gnuplot 仅在第一个和最后一个数据点的 x 轴上放置标记/标签? 最佳答案 在 gnuplot 4.6 及更高版本中,您可以使用命令 stats 'data.dat
我正在寻找一种方法来为具有共同词根/含义的单个词生成数值概率值。 用户将使用“舞者”、“跳舞”、“跳舞”等词生成内容。 如果“dancer”被提交了 30 次,跳舞了 5 次,我只需要一个值“danc
给定一个包含如下内容的数据集: [2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 65, 75, 85, 86, 87,
我想将声音的音高绘制成图表。 目前我可以绘制幅度。下图是由 getUnscaledAmplitude() 返回的数据创建的: AudioInputStream audioInputStream = A
在 Javascript 中,我试图获取一个初始的数值数组并计算其中的元素。理想情况下,结果将是两个新数组,第一个指定每个唯一元素,第二个包含每个元素出现的次数。不过,我愿意接受有关输出格式的建议。
我正在编写一个多线程OpenMPI应用程序,使用来自多个线程的MPI_Isend和MPI_Irecv在InfiniBand RDMA的各个列之间每秒交换数百条消息。 传输量约为400-800KByte
这个站点上有很多问题,询问如何在给定频率下创建简单的正弦波。我想做的是获取阵列或列表或任何频率,然后连续连续播放它们(而不是和弦),听起来有点像旧PC扬声器。我尝试使用Console.Beep,但是它
我使用我的App捕获声音。假设此声音是正弦1 KHz声音,并且存在背景声音。如何识别此1 KHz声音出现在声音上? 我的意思是,我可以想象如何在图像中找到元素,例如,如果您要在图像上寻找黄色正方形,那
我是一名优秀的程序员,十分优秀!