我想从文本文件中删除空行、点和逗号。我不太确定该怎么做。我尝试了不同的方法,但没有得到任何结果
filename = "phil.txt"
def countLines():
"""
Read number of lines in the text file.
"""
numOflines = 0
with open(filename) as file:
for line in file:
numOflines += 1
print("Total number of lines is: ", numOflines)
return numOflines
countLines()
我得到 19 行,但答案应该是 17 行。我另外我想要 还要删除逗号和点以供以后使用。
最佳答案
我会做类似的事情:
replaced_characters = {'\r\n': '\n', '\n\n': '\n', ',': ' ', '.':' ', ' ': ' '}
with open('file.ext', 'r') as f:
text = f.read()
for k, v in replaced_characters.items():
text = text.replace(k, v)
print(text)
我没有测试过。
关于python - 从文本文件中删除空行、点和逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58472527/