【问题标题】:Creating a Histogram from docx file [duplicate]从 docx 文件创建直方图 [重复]
【发布时间】:2023-03-11 09:31:01
【问题描述】:

我一直试图让这行代码工作。我是 python 新手,所以我不确定有多少问题。 Jupyter 一次只给出一个错误。无法弄清楚确切的问题。我不断收到第 16 行“打印计数器”的语法错误

我正在尝试从文件中导入文本并计算字母表中每个字母出现的次数。然后,我试图在直方图中绘制字母数。有什么想法吗?

import string
import sys
import matplotlib.pyplot as plt
%matplotlib inline 
from collections import Counter
from string import ascii_lowercase

def get_counts(fname):
# this function takes the name of a file as input parameter, fname
# it then reads the file into a string variable
# then proceeds to process the string for the count of letters
# answer should be returned in a list of 26 numbers

    with open('ra.docx') as f:
        print Counter(letter for line in f 
            for letter in line.lower() 
            if letter in ascii_lowercase)
        

def draw(counts):
# this function takes as input the "counts" list
# the function then proceeds to draw the histogram using matplotlib


    count = [1, 5, 10, 15, 20, 25, 30, 35, 40,45, 50, 55, 60]
    letters =["A","B","C","D","E","F","G","H","I","J", "K", "L", "M", "N","O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
    xaxis = range(len(letters))
    plt.figure(figsize=(12,8)) 
    plt.title("RA Text Histogram ")
    plt.xlabel("Letters")
    plt.ylabel("Count")
    plt.bar(xaxis, count, width=0.5)
    plt.xticks(xaxis, letters)
    for a,b in zip(xaxis, fall_enrollments):
    plt.text(a, b+20, str(b), horizontalalignment='center', verticalalignment='center')
    plt.show()

def main():
  #counts = get_counts(sys.argv[1])
  counts = get_counts("ra.txt")
  #print(counts)
  draw(counts)

main()

【问题讨论】:

    标签: python matplotlib syntax-error histogram


    【解决方案1】:

    print 作为语句(即print 后跟空格和字符串)是 Python 2 语法。如果您使用的是 Python 3(现在很有可能......),您必须使用 print() 函数:

    print(Counter(letter for line in f 
                  for letter in line.lower() 
                  if letter in ascii_lowercase))
    

    既然你已经导入了sys,那是什么

    sys.version
    

    返回?

    【讨论】:

    • 谢谢 - 这就是计数方面所需的全部内容。但是直方图仍然没有显示内容。即使它正在运行。它确实要求我缩进 plt.text 行,但除此之外,我不再收到任何错误或输出。我的代码中也没有看到 sys.version。
    • 好的,我可以立即发现的其他一些问题是,在您的 main() 函数中,您使用 "ra.txt" 调用 get_counts(),而在 get_counts() 的定义中,您硬编码了文件名 @ 987654332@。您在此处显示的代码真的是您执行的代码吗?否则,变量counts 似乎没有在draw() 的定义中使用。在那里,您对变量 count 进行了硬编码。是为了调试吗?我不太明白你的代码。
    • 另外,看看这个:stackoverflow.com/questions/52474028/…我想这就是你想要完成的,对吧?
    • 里面有几个错别字。我修复了 .txt 问题。我试图从绘图函数中提取输入,以便我导入的数据进入直方图。也许我需要在 draw 部分包含 counts 变量?
    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 2012-10-17
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多