gpt4 book ai didi

python - 在 Python 中计算换行符的问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:48:30 26 4
gpt4 key购买 nike

我在计算换行符时遇到了一个小问题。我正在开发一个程序,该程序应该计算 .txt 文件中的项目(字符、大写/小写字符等)。但是,我的行计数器计算的是字符数加一而不是新行数。例如,我得到的不是字符数 1048 和行数 37,而是字符数 1048 和行数 1049。我不确定我哪里搞砸了。

下面是相关代码。感谢任何帮助。

# initializing counters
char_count = 0
lower_count = 0
upper_count = 0
lines_count = 0
word_count = 0
prev_ch = ' '
is_prev_alnum = False



for ch in contents:
char_count += 1
if ch.islower():
lower_count += 1
if ch.isupper():
upper_count += 1
if ch == '\n':
lines_count += 1


# count words
if ch.isalnum():
if not is_prev_alnum:
word_count += 1
is_prev_alnum = True
else:
is_prev_alnum = False

if prev_ch != '\n':
lines_count += 1

prev_ch = ch

最佳答案

为什么会有

    if prev_ch != '\n':
lines_count += 1

由于 prev_ch 已经定义为 ' ' 或有效的 ch 它不是 '\n' , 它会像字符一样为每个循环不断计数

正如评论中所建议的,您可以只执行 if prev_ch == '\n'

关于python - 在 Python 中计算换行符的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com