Python读取文本文件提取指定标点返回空字符串的问题求解
问题排查与代码修正
原代码存在的问题
- 判断条件错误:
if c == punctations是判断单个字符和完整的标点字符串.,;:!?完全相等,该条件永远不成立,所以不会有字符被加入结果 - 字符串拼接逻辑错误:
- 字符串没有
append()方法,c.append(s)写法完全错误,且拼接方向搞反,应该是把符合要求的字符c拼接到结果s上,而不是反过来 - 你修改后的
s = + c写法错误,正确的累加拼接语法是s += c,等价于s = s + c
- 字符串没有
- 调用注意事项:示例里的调用写法
punctation('hello.txt')和定义的函数名punctuation不一致,少写了一个字母u,会触发名称报错。
修正后可运行代码
def punctuation(filename): # 建议指定编码避免不同环境读文件乱码 with open(filename, mode='r', encoding='utf-8') as f: s = '' punctuations = '''.,;:!?''' for line in f: for c in line: if c in punctuations: s += c return s
效果验证
如果hello.txt内容为Hello, how are you today?,调用punctuation('hello.txt')会返回,?,完全符合预期。
内容的提问来源于stack exchange,提问作者user15415514
相关产品推荐
相关产品推荐

