python:replace方法,两种不同的解决方案

python:replace方法,两种不同的解决方案,python,replace,Python,Replace,从带有“!”或“,”等字符的文件文本开始(基本上是整个字符串集。标点符号),我想删除它们,获得一个只包含所有单词的文本。 在这里,我找到了一个解决方案:我用以下方式编写了脚本: import string dict={} for elem in string.punctuation: dict[elem]="" def replace_all(text, dic): for i, j in dic.items(): text = text.replace(i,

从带有“!”或“,”等字符的文件文本开始(基本上是整个字符串集。标点符号),我想删除它们,获得一个只包含所有单词的文本。 在这里,我找到了一个解决方案:我用以下方式编写了脚本:

import string

dict={}
for elem in string.punctuation:
    dict[elem]=""

def replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text

with open ("text.txt","r") as f:
    file = f.read()
    f = replace_all(file,dict)

print(f)
好的,这是可行的,但如果我尝试另一种解决方案,我将不会得到相同的结果:

with open ("text.txt","r") as f:
    file = f.read()
    for elem in string.punctuation:
        if elem in file:
            f=file.replace(elem,"")

在这种情况下,如果我输入print(f),我就有了完全相同的文件和所有标点符号。为什么?

我会使用过滤器搜索和替换多个项目:

import string
testString = "Hello, world!"
print(str(filter(lambda a: a not in string.punctuation, testString)))
正则表达式 如果要删除所有非字母数字字符,最好使用正则表达式:

import string, re
testString = "Hello, world!"
print(re.sub("[^\w ]", "", testString))
为什么你的代码不起作用 两个主要问题:

  • 您正在重新分配
    f
    而不是
    文件
  • 您没有打印
    文件
    ,因此我添加了行
    打印(文件)
  • 新代码:

    import string
    
    with open ("text.txt","r") as f:
        file = f.read()
        for elem in string.punctuation:
            if elem in file:
                file=file.replace(elem,"")
        print(file)
    

    好的,谢谢,但是我想了解为什么第二种解决方案没有产生任何效果,我正在学习pythonI添加了一个新的部分。如果您可以标记为解决方案,这将非常有用。在第二个版本中,每次执行
    f=file.replace(elem,“”)
    时,您将使用原始文件,只替换
    elem
    的当前值。如果您更仔细地查看输出,我怀疑文件中的
    string.parantion
    中的最后一个元素已被删除。使用
    str.translate()
    ,这是迄今为止最有效的方法。多亏了大家,我看到了这篇重复的文章,但这里的问题不是哪种方法效果更好(当然有很多),而是我必须理解第二个脚本中for的内部发生了什么