如何让python读取文本文件并返回lines
,characters
,vowels
,consonants
,lowercase letters
和uppercase letters
的数量
编写一个接受文件名作为命令行参数的程序。 (可以假定输入文件将是纯文本文件。 如果用户忘记包含命令行参数,则程序应退出并显示相应的错误消息。
否则,程序应打印出:
- 文件中的行数
- 文件中的字符数
- 文件中的元音数(出于此赋值的目的,将"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()
获取行数组(作为字符串)
法典
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))