嗨,所以我有2个文本文件,我要读第一个文本文件计数每个单词的频率,删除重复项,并创建一个列表,其中包含单词及其在文件中的计数。在
我的第二个文本文件包含关键字,我需要计算第一个文本文件中这些关键字的频率,并返回结果,而不使用任何导入、dict或zips。在
我被困在如何进行这第二部分我有文件打开和删除标点等,但我不知道如何找到频率
我想了想.find()
但还没有运气。在
任何建议将不胜感激这是我的代码目前似乎在关键字文件中查找关键字的频率而不是在第一个文本文件中
def calculateFrequenciesTest(aString):
listKeywords= aString
listSize = len(listKeywords)
keywordCountList = []
while listSize > 0:
targetWord = listKeywords [0]
count =0
for i in range(0,listSize):
if targetWord == listKeywords [i]:
count = count +1
wordAndCount = []
wordAndCount.append(targetWord)
wordAndCount.append(count)
keywordCountList.append(wordAndCount)
for i in range (0,count):
listKeywords.remove(targetWord)
listSize = len(listKeywords)
sortedFrequencyList = readKeywords(keywordCountList)
return keywordCountList;
编辑-目前正在考虑重新打开我的第一个文件,但这次没有把它变成一个列表?我想我的错误是从某种程度上源于它计算我的列表的频率。这些是我得到的结果类型
^{pr2}$
我同意@bereal的观点,您应该使用}。在
Counter
。我知道你说过你不想要“进口、dict或zips”,所以你可以忽略这个答案。然而,Python的一个主要优点是它的标准库,每次你有list
可用时,你也会有dict
、collections.Counter
和{从您的代码中我得到的印象是,您希望使用与C或Java相同的样式。我建议你多做一点。以这种方式编写的代码可能看起来不太熟悉,而且需要时间来适应。不过,你会学到更多。在
你想要达到的目标会有所帮助。你在学Python吗?你在解决这个具体问题吗?你为什么不能用进口货,dict或zips?在
因此,这里有一个利用内置功能(没有第三方)的建议(使用Python2测试):
你可以尝试一下:
我以一个单词表为例。在
既然你对dicts施加了限制,我就利用两个列表来完成同样的任务。我不知道它的效率有多高,但它是有用的。在
^{pr2}$你可以把它改成你喜欢的样子,或者根据你的意愿重新考虑它
这是一个没有进口的解决方案。它使用嵌套的线性搜索,在一个小的输入数组上进行少量的搜索是可以接受的,但是当输入较大时会变得笨拙和缓慢。在
这里的输入仍然很大,但是它在合理的时间内处理它。我怀疑如果你的关键字文件更大(我的只有3个字)减速将开始显示。在
这里我们获取一个输入文件,遍历行并删除标点符号,然后按空格分割并将所有单词展平到一个列表中。列表中有重复项,因此要删除它们,我们对列表进行排序,使重复项聚集在一起,然后在列表上进行迭代,创建一个包含字符串和计数的新列表。我们可以通过增加计数来做到这一点,只要同一个单词出现在列表中,并在看到新单词时移动到新条目。在
现在,你有了你的词频列表,你可以在其中搜索所需的关键字并检索计数。在
输入的文本文件是here,关键字文件可以用文件中的几个单词拼凑在一起,每行一个。在
python3代码,它指示在适用的情况下如何为python2修改。在
如果您愿意,可以修改
findword
以使用二进制搜索,但它仍然不会接近dict
。collections.Counter
是没有限制的正确解决方案。它更快、更少的代码。在相关问题 更多 >
编程相关推荐