如何让python读取文本文件并返回lines
,characters
,vowels
,consonants
,lowercase letters
和{{1 }}
编写一个接受文件名作为命令行参数的程序。 (您可以假设输入文件将是纯文本文件。)如果用户忘记包含命令行参数,则程序应退出并显示相应的错误消息。
否则,您的程序应打印出来:
我输了。我该怎么做?就像我很确定有命令可以做到这一点,但我不知道它们是什么。谢谢你的帮助:)
修改 这是我的最终计划和完美。感谢大家的帮助。特别感谢Bentaye:)
uppercase letters
答案 0 :(得分:1)
这可以解决您的问题,现在可以针对大/小的情况构建它
sys.argv[0]
捕获参数(您需要导入sys
)file.readlines()
获取一系列行(如字符串)<强>代码强>
import sys
countV = 0
countC = 0
lines = 0
characters = 0
vowels = set("AEIOUaeiou")
cons = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")
with open(sys.argv[0]) 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
print("Lines: " + str(lines))
print("Characters: " + str(characters))
print (countV)
print (countC)
你这么称呼它
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))