当我使用代码时,这个程序运行得很好
for character in infile.readline():
问题是readline只读取一行文本。当我在readline命令中添加“s”时
^{pr2}$我最终得到的是我的输出。在
os.chdir(r'M:\Project\Count')
def main():
infile = open("module3.txt","r")
uppercasecount = 0
lowercasecount = 0
digitcount = 0
spacecount = 0
for character in infile.readlines():
if character.isupper() == True:
uppercasecount += 1
if character.islower() == True:
lowercasecount += 1
if character.isdigit() == True:
digitcount += 1
if character.isspace() == True:
spacecount += 1
print ("Total count is %d Upper case, %d Lower case, %d Digit(s) and %d spaces." %(uppercasecount, lowercasecount, digitcount, spacecount))
main()
另外,如果有人能给我建议,我可以把这个目录设为默认位置,这样我就可以把它用在别人的机器上了吗。在
如果您只想检查文件中包含的字符类型,我不会使用readlines,而是使用常规的read。在
如果您真的需要使用
readlines
,请记住,该方法将读取文件的所有行,并将它们放入内存中(对于非常大的文件,则不太适合)。在例如,假设您的
^{pr2}$module3.txt
文件包含:使用
readlines()
将返回:记住这一点,您可以使用双
for
循环遍历文件内容:至于目录问题,如果代码和文本文件(
module3.txt
)将在同一目录中提供,则不需要执行chdir
。默认情况下,脚本的工作目录是脚本所在的目录。在假设您将其发送到一个目录中,例如:
您只需使用相对路径从
script.py
中打开module3.txt
:行open("module3.txt", "r")
将使用脚本运行的目录查找名为module3.txt
的文件(即Count\
)。您不需要调用os.chdir
。如果您还想确定,可以chdir
到脚本所在的目录(查看this):知道了这一点,请将您的硬编码
chdir
行(文件顶部的os.chdir(r'M:\Project\Count')
)更改为:您可以使用两种形式
iter
一次读取任意数量的字节,使用itertools.chain
将它们视为一个长输入。您可以使用str
方法作为collections.Counter
的键,而不是跟踪几个变量,例如:那么
counts[str.lower]
会给你39
例如。。。在相关问题 更多 >
编程相关推荐