Python字符计数器仅统计第一行,如何实现多行字符统计?
问题分析
- 多行读取失效问题:Python的
input()函数设计为读取单行输入,遇到换行符就会终止读取,所以你输入多行内容时只能拿到第一行数据。 - 隐藏bug1:Python字符串为不可变类型,
replace()方法不会修改原字符串,只会返回替换后的新字符串,你当前代码中的替换操作没有赋值回原变量,所有过滤规则完全不生效。 - 隐藏bug2:数学符号、括号、其他字符的三项判断条件错误引用了
whatTo3Do变量,导致这三项的设置不会生效。
修复后的完整代码
import time import sys print("Please answer Y or N to the following questions:") whatTo1Do = input("Would you like to include spaces in the character count? " ) whatTo2Do = input("Would you like to include commas in the character count? " ) whatTo3Do = input("Would you like to include apostrophes in the character count? " ) whatTo4Do = input("Would you like to include maths symbols (+, <, ÷, etc.) in the character count? " ) whatTo5Do = input("Would you like to include brackets in the character count? " ) whatTo6Do = input("Would you like to include other characters (~, `, \, %, &, etc.) in the character count? " ) yas = input("Your settings are displayed above. Are they correct? ") if yas == "Y": pass elif yas == "N": print("Please press OK to restart.") time.sleep(1) exit() # 支持多行读取的输入逻辑 print("Enter your text here to count the characters based on your settings above: ") print("(输入完成后:Windows系统按Ctrl+Z再按回车,macOS/Linux系统按Ctrl+D)") text = sys.stdin.read() # 修正替换逻辑与判断条件 if whatTo1Do.lower() in ("n", "no"): text = text.replace(" ", "") if whatTo2Do.lower() in ("n", "no"): text = text.replace(",", "") if whatTo3Do.lower() in ("n", "no"): text = text.replace("'", "").replace('"', "") if whatTo4Do.lower() in ("n", "no"): for c in ("×", "÷", "=", "-", "+", ">", "<", "^", "*"): text = text.replace(c, "") if whatTo5Do.lower() in ("n", "no"): for c in ("[", "]", "(", ")", "{", "}"): text = text.replace(c, "") if whatTo6Do.lower() in ("n", "no"): for c in ("~", "`", "@", "#", "$", "%", "&", "\\", "|", "/"): text = text.replace(c, "") print("There are", len(text), "characters in your text. (=")
改动说明
- 引入
sys模块,用sys.stdin.read()替代input()读取输入,会读取所有输入内容直到结束符,支持包含换行的多行内容。 - 所有
replace()操作的结果都赋值回text变量,替换逻辑生效。 - 修正了4、5、6项设置的判断条件,同时用
lower()统一转小写判断,简化了判断逻辑。 - 把重复的replace操作改成循环遍历,代码更简洁易维护。
- 修正了反斜杠字符的转义写法,避免转义错误。
内容的提问来源于stack exchange,提问作者red-back spider
相关产品推荐
相关产品推荐

