【问题标题】:Python Concordance program - alphabetical orderPython Concordance 程序 - 按字母顺序
【发布时间】:2014-05-02 15:58:03
【问题描述】:

我正在尝试编写一个显示文件索引的程序。它应该按字母顺序输出唯一的单词及其频率。这就是我所拥有的,但它不起作用。提示?

仅供参考 - 我对计算机编程一无所知!我参加这门课是为了满足高中数学认可的要求。

f = open(raw_input("Enter a filename: "), "r")
myDict = {}
linenum = 0

for line in f:
  line = line.strip()
  line = line.lower()
  line = line.split()
  linenum += 1

for word in line:
    word = word.strip()
    word = word.lower()

    if not word in myDict:
        myDict[word] = []

    myDict[word].append(linenum)


print "%-15s %-15s" %("Word", "Line Number")
for key in sorted(myDict):
    print '%-15s: %-15d' % (key, myDict(key))

【问题讨论】:

  • 给定输入的输出到底是什么?如果不确切地告诉我们为什么它不起作用,只是说“它不起作用”并没有多大帮助。
  • 您需要使用 myDict[key] 从字典中获取。由于这是一个列表,因此您需要使用 sum(myDict[key]) 作为频率(计数)

标签: python alphabetical-sort


【解决方案1】:

您需要使用 myDict[key] 从字典中获取。由于这是一个列表,因此您需要使用 sum(myDict[key]) 作为频率(计数)

f = "HELLO HELLO HELLO WHAT ARE YOU DOING"
myDict = {}
linenum = 0

for word in f.split():
    if not word in myDict:
        myDict[word] = []

    myDict[word].append(linenum)


print "%-15s %-15s" %("Word", "Frequency")
for key in sorted(myDict):
    print '%-15s: %-15d' % (key, len(myDict[key]))

结果:

Word            Frequency
ARE            : 1
DOING          : 1
HELLO          : 3
WHAT           : 1
YOU            : 1

【讨论】:

    【解决方案2】:

    你的缩进错误。第二个循环在第一个循环之外,所以它只在最后一行工作。 (您应该考虑使用 4 个空格来更好地查看它)。您的打印也有误,您打印的是行号,而不是字数。

    myDict = {}
    linenum = 0
    
    for line in f:
        line = line.strip()
        line = line.lower()
        line = line.split()
        linenum += 1
        for word in line:
            word = word.strip()
            word = word.lower()
    
            if not word in myDict:
                myDict[word] = []
            myDict[word].append(linenum)
    print "%-15s %5s  %s" %("Word", 'Count', "Line Numbers")
    for key in sorted(myDict):
        print '%-15s %5d: %s' % (key, len(myDict[key]), myDict[key])
    

    样本输出:

    Word            Count  Line Numbers
    -                   1: [6]
    a                   4: [2, 2, 3, 7]
    about               1: [6]
    alphabetical        1: [4]
    

    编辑更正代码中的错误

    【讨论】:

    • 这个程序没有按预期运行。 Word 消失了,Count 的值显示超出预期。尝试您的程序并设置 f="aa 所有字母顺序和出现。任意奖励:一致性,记录每个英语,频率。生成给定的即在标签中标记的列表数字出现次数,程序句子文本,其中将带有单词字字写写”
    • 再来?我不太明白你的评论。
    • 可能是我的 Python 版本(2.6.7 或更低版本),但是当我尝试上面的代码并设置上面评论中提到的“f”变量的值时,它没有打印输出如您的“示例输出”所示。
    • f 应该是打开的文本文件对象或行列表
    【解决方案3】:

    这是我的一致性解决方案......

    https://github.com/jrgosalia/Python/blob/master/problem2_concordance.py

    $ python --version Python 3.5.1

    库.py

    def getLines(fileName):
        """ getLines validates the given fileName.
            Returns all lines present in a valid file. """
        lines = ""
        if (fileName != None and len(fileName) > 0 and os.path.exists(fileName)):
            if os.path.isfile(fileName):
                file = open(fileName, 'r')
                lines = file.read()
                if (len(lines) > 0):
                    return lines
                else:
                    print("<" + fileName + "> is an empty file!", end="\n\n")
            else:
                print("<" + fileName + "> is not a file!", end="\n\n")
        else:
            print("<" + fileName + "> doesn't exists, try again!", end="\n\n")
        return lines
    

    problem2_concordance.py

    from library import getLines
    
    # List of English Punctuation Symbols
    # Reference : Took maximum puntuations symbols possible from https://en.wikipedia.org/wiki/Punctuation_of_English
    # NOTE: Apostrophe is excluded from the list as having it or not having it will give always distinct words.
    punctuations = ["[", "]", "(", ")", "{", "}", "<", ">", \
             ":", ";", ",", "`", "'", "\"", "-", ".", \
             "|", "\\", "?", "/", "!", "-", "_", "@", \
             "\#", "$", "%", "^", "&", "*", "+", "~", "=" ]
    
    def stripPunctuation(data):
        """ Strip Punctuations from the given string. """
        for punctuation in punctuations:
            data = data.replace(punctuation, " ")
        return data
    
    def display(wordsDictionary):
        """ Display sorted dictionary of words and their frequencies. """
        noOfWords = 0
        print("-" * 42)
        print("| %20s | %15s |" % ("WORDS".center(20), "FREQUENCY".center(15)))
        print("-" * 42)
        for word in list(sorted(wordsDictionary.keys())):
            noOfWords += 1
            print("| %-20s | %15s |" % (word, str(wordsDictionary.get(word)).center(15)))
            # Halt every 20 words (configurable)
            if (noOfWords != 0 and noOfWords % 20 == 0):
                print("\n" * 2)
                input("PRESS ENTER TO CONTINUE ... ")
                print("\n" * 5)
                print("-" * 42)
                print("| %20s | %15s |" % ("WORDS".center(20), "FREQUENCY".center(15)))
                print("-" * 42)
        print("-" * 42)
        print("\n" * 2)
    
    def prepareDictionary(words):
        """ Prepare dictionary of words and count their occurences. """
        wordsDictionary = {}
        for word in words:
            # Handle subsequent Occurences
            if (wordsDictionary.get(word.lower(), None) != None):
                # Search and add words by checking their lowercase version
                wordsDictionary[word.lower()] = wordsDictionary.get(word.lower()) + 1
            # Handle first Occurence
            else:
                wordsDictionary[word.lower()] = 1
        return wordsDictionary
    
    def main():
        """ Main method """
        print("\n" * 10)
        print("Given a file name, program will find unique words and their occurences!", end="\n\n");
        input("Press ENTER to start execution ... \n");
    
        # To store all the words and their frequencies
        wordsDictionary = {}
        lines = ""
        # Get valid input file
        while (len(lines) == 0):
            fileName = input("Enter the file name (RELATIVE ONLY and NOT ABSOLUTE): ")
            print("\n\n" * 1)
            lines = getLines(fileName)
        # Get all words by removing all puntuations
        words = stripPunctuation(lines).split()
        # Prepare the words dictionary
        wordsDictionary = prepareDictionary(words)
        # Display words dictionary
        display(wordsDictionary)
    
    """
        Starting point
    """
    main()
    

    注意:您还需要 library.py 来执行上述代码,该代码也存在于同一个 github 存储库中。

    【讨论】:

    • 您应该将代码添加到上面的帖子中。拥有将来可能不存在的链接并不是一个好的回答方式。
    • 这是我的第一篇文章,我尝试粘贴我的代码,但编辑器扭曲了我的代码,它无法区分 cmets 和实际代码,所以我创建了自己的 github 存储库,以便它可以保存格式化的代码。格式化的代码很容易阅读。如果我在这里粘贴代码时遗漏了什么,请告诉我...
    【解决方案4】:

    你为什么不直接使用计数器?这就是它的用途:

    In [8]: s = 'How many times does each word show up in this sentence word word show up up'
    
    In [9]: words = s.split()
    
    In [10]: Counter(words)
    Out[10]: Counter({'up': 3, 'word': 3, 'show': 2, 'times': 1, 'sentence': 1, 'many': 1, 'does': 1, 'How': 1, 'each': 1, 'in': 1, 'this': 1})
    

    注意:我不能把这个特定的解决方案归功于我。它直接来自Collections Module counter Python Bootcamp

    【讨论】:

      【解决方案5】:

      文本文件的一致性,按字母顺序排列;

      f=input('Enter the input file name: ')
      inputFile = open(f,"r")
      list={}
      for word in inputFile.read().split():
          if word not in list:
              list[word] = 1
          else:
                  list[word] += 1
                  inputFile.close();
      for i in sorted(list):
          print("{0} {1} ".format(i, list[i]));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-09
        • 2013-05-18
        • 1970-01-01
        • 2020-04-16
        • 2012-11-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多