Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 Python对具有列表中单词的多个副本_Python 2.7_List_Jython 2.7 - Fatal编程技术网

Python 2.7 Python对具有列表中单词的多个副本

Python 2.7 Python对具有列表中单词的多个副本,python-2.7,list,jython-2.7,Python 2.7,List,Jython 2.7,因此,我有以下代码: def stripNonAlphaNum(text): import re return re.compile(r'\W+', re.UNICODE).split(text) def readText(fileStub): words = open(fileStub, 'r').read() words = words.lower() # Make it lowercase wordlist = sorted(stripNonAlphaNum(

因此,我有以下代码:

def stripNonAlphaNum(text):
    import re
    return re.compile(r'\W+', re.UNICODE).split(text)

def readText(fileStub):
  words = open(fileStub, 'r').read()
  words = words.lower() # Make it lowercase
  wordlist = sorted(stripNonAlphaNum(words))
  wordfreq = []
  for w in wordlist: # Increase count of one upon every iteration of the word.
    wordfreq.append(wordlist.count(w))
  return list(zip(wordlist, wordfreq))
它读入一个文件,然后生成成对的单词和它们出现的频率。我面临的问题是,当我打印结果时,我没有得到正确的对计数

如果我有一些输入,我可能会得到如下输出:

(‘and’,27),(‘and’,27),(‘and’,27),(‘and’,27),(‘and’,27),(‘and’,27),(‘and’,27),(‘and’,27),(‘and’,27),。。(27次)

这不是我想要它做的

相反,我希望它输出1个单词和一个数字,如下所示:

('and',27),('able',5),('bat',6)。。等


<> P> >我如何解决这个问题?

< P>你应该考虑使用字典。 字典的工作方式类似于散列映射,因此允许关联索引;这样,就不会出现重复的问题

...
  wordfreq = {}
  for w in wordlist: 
    wordfreq[w] = wordlist.count(w)
  return wordfreq
如果确实需要返回列表,只需执行
returnwordfreq.items()

这种方法唯一的问题是,对于每个单词,您将不必要地多次计算wordlist.count()方法。 为避免此问题,请在集合(单词列表)中为w编写


编辑其他问题:如果您可以返回列表,只需执行
returnsorted(wordfreq.items(),key=lambda t:t[1])
。如果省略关键部分,结果将首先按单词排序,然后按值排序

这非常有效!一次编辑如果你能做到,我如何使字典中的项目按照项目数量和字母顺序排序?因此,对于所有以“1”为值的内容,我需要按字母顺序排序,依此类推。编辑答案,希望它符合您的需要