如何使用JES(学生用Python)计算文件中的字符数
如何让python读取文本文件并返回行数、字符、元音、辅音、小写字母和大写字母 编写一个接受文件名作为命令行参数的程序。您可以假定输入文件是纯文本文件。如果用户忘记包含命令行参数,则程序应退出并显示相应的错误消息 否则,您的程序应打印出: 文件中的行数 文件中的字符数 文件中的元音数在本赋值中,将y视为辅音。 文件中辅音的数量 文件中的小写字母数 文件中大写字母的数量 我不知所措。我该怎么做?就像我很确定有一些命令可以做到这一点,但我不知道它们是什么。感谢您的帮助: 编辑 这是我的最后一个节目,非常完美。谢谢大家的帮助。特别感谢Bentaye:如何使用JES(学生用Python)计算文件中的字符数,python,file,text,jes,Python,File,Text,Jes,如何让python读取文本文件并返回行数、字符、元音、辅音、小写字母和大写字母 编写一个接受文件名作为命令行参数的程序。您可以假定输入文件是纯文本文件。如果用户忘记包含命令行参数,则程序应退出并显示相应的错误消息 否则,您的程序应打印出: 文件中的行数 文件中的字符数 文件中的元音数在本赋值中,将y视为辅音。 文件中辅音的数量 文件中的小写字母数 文件中大写字母的数量 我不知所措。我该怎么做?就像我很确定有一些命令可以做到这一点,但我不知道它们是什么。感谢您的帮助: 编辑 这是我的最后一个节目,
import sys
def text():
countV = 0
countC = 0
lines = 0
countU = 0
countL = 0
characters = 0
vowels = set("AEIOUaeiou")
cons = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")
upper = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
lower = set("abcdefghijklmnopqrstuvwxyz")
with open(sys.argv[1]) as file:
fileLines = file.readlines()
for line in fileLines:
lines = lines + 1
characters = characters + len(line)
for char in line:
if char in vowels:
countV = countV + 1
elif char in cons:
countC = countC + 1
for char in line:
if char in upper:
countU = countU + 1
elif char in lower:
countL = countL + 1
print("Lines: " + str(lines))
print("Characters: " + str(characters))
print("Vowels: " + str(countV))
print("Consonants: " + str(countC))
print("Lowercase: " + str(countL))
print("Uppercase: " + str(countU))
text()
这解决了您的问题,您现在可以在上面构建大写/小写 使用sys.argv[0]捕获导入sys所需的参数 然后使用file.readlines以字符串形式获取行数组 代码 你这么说
python test.py yourFile.txt
完整答案供参考
您对此做过任何研究吗?以字符串列表的形式读取文件,每行一个字符串,逐个字符迭代,并根据每个字符递增计数器。试试看,然后用你的代码更新你的问题,我们会帮助你的。从这里开始:使用argparse获取命令行参数,迭代每个字符并进行处理。编写一些代码,如果您不能,我们将帮助您。@Sam我将其作为编辑添加到您的问题中。你几乎已经在那里了。你已经使用这个网站找到了其他类似的问题,但我从来没有问过任何问题,所以我不知道程序。非常感谢你,如果我需要进一步的帮助,我会让你知道。我能做些什么来提高你在这个网站上的信誉吗?@Sam你也可以投票回答:如果你需要更多帮助,请在这里发表评论。另外,我也不确定如何处理空格和其他特殊字符括号、逗号等,我想它们不算小写。请注意这一点
python test.py yourFile.txt
import sys
vowels = "aeiou"
cons = "bcdfghjklmnpqrstvwxyz"
with open(sys.argv[0]) as file:
fileLines = file.readlines()
countVowels = 0
countConsonants = 0
countUpperCase = 0
countLowerCase = 0
countLines = 0
countCharacters = 0
countNonLetters = 0
for line in fileLines:
countLines += 1
countCharacters = countCharacters + len(line)
for char in line:
if char.isalpha():
if char.lower() in vowels:
countVowels += 1
elif char.lower() in cons:
countConsonants += 1
if char.isupper():
countUpperCase += 1
elif char.islower():
countLowerCase += 1
else:
countNonLetters += 1
print("Lines: " + str(countLines))
print("Characters: " + str(countCharacters))
print("Vowels: " + str(countVowels))
print("Consonants: " + str(countConsonants))
print("Upper case: " + str(countUpperCase))
print("Lower case: " + str(countLowerCase))
print("Non letters: " + str(countNonLetters))