【问题标题】:python not removing punctuationpython没有删除标点符号
【发布时间】:2020-05-14 15:10:47
【问题描述】:

我有一个文本文件,我想删除标点符号并将其另存为新文件,但它没有删除任何内容,知道为什么吗?

代码:

def punctuation(string):
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

    for x in string.lower():
        if x in punctuations:
            string = string.replace(x, "")

            # Print string without punctuation
    print(string)


file = open('ir500.txt', 'r+')
file_no_punc = (file.read())

punctuation(l)

with open('ir500_no_punc.txt', 'w') as file:
    file.write(file_no_punc)

为什么要去掉标点符号?

【问题讨论】:

  • 你重新分配字符串;您不会更改原始实例(您不能:字符串是不可变的)。您是要返回更改后的字符串吗?也看看str.maketransstr.translate
  • 任何答案对您有帮助吗?如果是这样,请单击旁边的勾号接受音调。这样做将有助于这个问题的未来读者,就像你得到帮助一样。

标签: python-3.x file text punctuation txt2tags


【解决方案1】:
def punctuation(string):
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

    for x in string.lower():
        if x in punctuations:
            string = string.replace(x, "")

    # return string without punctuation
    return string



file = open('ir500.txt', 'r+')
file_no_punc = (file.read())

file_no_punc = punctuation(file_no_punc)

with open('ir500_no_punc.txt', 'w') as file:
    file.write(file_no_punc)

解释:

我只将punctuation(l) 更改为file_no_punc = punctuation(file_no_punc)print(string) 更改为return string

1) punctuation(l) 中的 l 是什么?
2) 您正在调用 punctuation() - 它可以正常工作 - 但不要使用它的返回值
3)因为它当前没有返回值,只是打印它;-)

请注意,我只进行了最小的更改以使其正常工作。您可能想将其发布到我们的code review 网站,看看如何改进。

另外,我建议您获得一个好的 IDE。在我看来,你无法击败PyCharm 社区版。了解如何使用调试器;它是你最好的朋友。设置断点,运行代码;它会在遇到断点时停止;然后,您可以检查变量的值。

【讨论】:

  • 哈哈!多么尴尬。已更正,感谢 (+1) 顺便说一句,喜欢你的手柄;好书!
【解决方案2】:

取出文件读/写,你可以像这样从字符串中删除标点符号:

table = str.maketrans("", "", r"!()-[]{};:'\"\,<>./?@#$%^&*_~")

# # or maybe even better
# import string
# table = str.maketrans("", "", string.punctuation)

file_with_punc = r"abc!()-[]{};:'\"\,<>./?@#$%^&*_~def"
file_no_punc = file_with_punc.lower().translate(table)
# abcdef

我在哪里使用str.maketransstr.translate

请注意,python 字符串是不可变的。无法更改给定的字符串;您对字符串执行的每个操作都会返回一个新实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    相关资源
    最近更新 更多