我正在努力为文件选择制作包含 easygui 的单词计数器程序。我目前使用带有PyDev插件的Eclipse SDK(如果有更好的Python环境的建议)。
以下是我当前状态的代码:
#This program is supposed to take a word file, and count the amount of lines and
#words. If the entered file is not a .txt, .doc, or .docx, then the program will
#ask for a different file.
from easygui import fileopenbox
filename = fileopenbox()
lines, words = 0, 0
#This method will count the amount of lines and words in a program and display
#it to the user
def word_count():
if filename.endswith('.docx'): #If the file extension is .docx
print("Your file has" + num_words + "words") #Print the amount of lines and words in the file.
elif filename.endswith('.doc'): #If the file extension is .doc
#<CODE WHICH COUNTS LINES AND WORDS>
print("Your file has", lines, "lines, and" ,"words") #Print the amount of lines and words in the file.
elif filename.endswith('.txt'): #If the file extension is .txt
#<CODE WHICH COUNTS LINES AND WORDS>
print("Your file has", lines, "lines, and" ,"words") #Print the amount of lines and words in the file.
elif filename.endswith('.py'): #If the file extension is .py
#<CODE WHICH COUNTS LINES AND WORDS>
print("Your file has", lines, "lines, and" ,"words") #Print the amount of lines and words in the file.
elif filename.endswith('.java'): #If the file extension is .java
#<CODE WHICH COUNTS LINES AND WORDS>
print("Your file has", lines, "lines, and" ,"words") #Print the amount of lines and words in the file.
else:
print("Are you trying to annoy me? How about giving me a TEXT or SOURCE CODE file, genius?")#Print an insulting error message.
如代码所示,我希望程序读取文件扩展名,如果匹配其中任何一个,请运行单词count代码。但是,我的问题是,那个字数代码是什么?似乎使用easygui中的fileopenbox()会使事情变得更加复杂。感谢提前感谢任何帮助
答案 0 :(得分:1)
from easygui import fileopenbox
def word_count(filename):
if not filename.endswith(('.txt', '.py', '.java')):
print('Are you trying to annoy me? How about giving me a TEXT or SOURCE CODE file, genius?')
return
with open(filename) as f:
n_lines = 0
n_words = 0
for line in f:
n_lines += 1
n_words += len(line.split())
print('Your file has {} lines, and {} words'.format(n_lines, n_words))
filename = fileopenbox()
word_count(filename)