从 docx 文件创建直方图[重复]

问题描述 投票:0回答:1

我一直在尝试让这行代码正常工作。我是 python 新手,所以我不确定有多少问题。 Jupyter 一次只给出一个错误。无法弄清楚具体的问题。我不断收到第 16 行“print Counter”的语法错误

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

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个回答
0
投票

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

返回?

© www.soinside.com 2019 - 2024. All rights reserved.