python - 从文本文件中删除空行、点和逗号

标签 python

我想从文本文件中删除空行、点和逗号。我不太确定该怎么做。我尝试了不同的方法,但没有得到任何结果

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/

相关文章:

python - 进程卡在 SQS 调用中

python - 将集合转换为列表时,什么决定项目顺序?

python - 如何在 python 中交换值?

python - Intellij 中未正确检测到 Python 文件并且缺少语法突出显示

python - 改进 Python 中点云空间感知中值滤波器的方法

python - pandas 将 2 个具有不同日期索引的数据帧组合在一起

python - 如何在 Python 中索引 0-d 数组?

python - wxPython - StyledTextCtrl 获取当前可见行

python - 检查 OrderedDict 字典中是否存在该项目

Python OpenCV - 用透明度覆盖图像