你怎么算空格的字符?我没有得到正确的号码。 num_charsx的正确数量是1761
num_words = 0
num_chars = 0
with open("C:/Python33/fire.txt",'r') as f:
for line in f:
words = line.split('\n')
num_words += len(words)
num_chars += len(line)
num_charsx = num_chars - line.count(' ')
print(num_charsx)
2064
答案 0 :(得分:0)
您可能希望尝试使用''而不是'\ n'来分割线条。因为'\ n'应该由for循环完成。
另一个选项,如果你只想要一个字符数,你可以使用replace方法删除''然后计算字符串的长度。
num_chars = len(line.replace(' ', ''))
答案 1 :(得分:0)
你也可以试试这个:
num_chars = 0
with open("C:/Python33/fire.txt",'r') as f:
for line in f:
num_chars += len(line.split('\n')[0])
num_charsx = num_chars - line.count(' ')
print(num_charsx)
答案 2 :(得分:0)
words = line.split('\n')
num_words += len(words)
不符合您的想法。在循环中
for line in f:
line
是一个以'\n'
结尾的字符串,因此line.split('\n')
是一个两项列表,第一项包含除终止之外的所有行的字符{{ 1}};该列表中的第二项是空字符串。例如:
'\n'
<强>输出强>
line = 'This is a test\n'
words = line.split('\n')
print(words, len(words))
所以你的['This is a test', ''] 2
实际上没有计算单词,它只是得到行数的两倍。
获取num_words += len(words)
中您需要的单词的实际列表
line
倒数第二行
words = line.split()
在num_charsx = num_chars - line.count(' ')
循环之外,所以它从总for
中减去文件最后一行的空间计数,但我假设你真的想减去整个文件的总空间数来自num_chars
。
这是修复后的代码版本。
num_chars
我修改了行读取循环以使用num_words = 0
num_chars = 0
num_spaces = 0
with open(fname, 'r') as f:
for num_lines, line in enumerate(f, 1):
num_words += len(line.split())
num_chars += len(line) - 1
num_spaces += line.count(' ')
num_charsx = num_chars - num_spaces
print(num_lines, num_words, num_chars, num_spaces, num_charsx)
。这是获取行号和行内容的有效方法,无需维护单独的行计数器。
在enumerate
num_chars += len(line) - 1
中,我们不会在字数统计中包含每行的终止-1
。
请注意,在Windows上,文本文件行(通常)以'\n'
终止,但当您读取以文本模式打开的文件时,该终结符将转换为'\r\n'
。所以在Windows上,文件的实际字节大小为'\n'
,假设最后一行有一个num_chars + 2 * num_lines
终结符;它可能不会,在这种情况下,实际大小将比该小2个字节。
答案 3 :(得分:0)
你可以试试这个:
num_char = 0
f = open("C:/Python33/fire.txt")
word_list = ' '.join(f.read().splitlines()).split()
for x in word_list:
num_char += len(x)
print(num_char)