【问题标题】:How to replace the puntuation marks in words with effective code? [duplicate]如何用有效的代码替换单词中的标点符号? [复制]
【发布时间】:2017-01-11 09:11:57
【问题描述】:

我一直在处理一个包含很多标点符号的文件,我们需要忽略标点符号,以便计算单词的实际长度。

例子:

这是堆栈溢出吗! ---> 这是堆栈溢出吗

在这样做的同时,我确实为每个标点符号写了很多案例,这使我的代码运行缓慢。所以我正在寻找一些有效的方法来使用模块或函数来实现相同的目标。

代码 sn-p:

with open(file_name,'r') as f:
     for line in f:
         for word in line.split():
            #print word
            '''
                Handling Puntuations
            '''
            word = word.replace('.','')
            word = word.replace(',','')
            word = word.replace('!','')
            word = word.replace('(','')
            word = word.replace(')','')
            word = word.replace(':','')
            word = word.replace(';','')
            word = word.replace('/','')
            word = word.replace('[','')
            word = word.replace(']','')
            word = word.replace('-','')

所以形成这个逻辑我已经写了这个,那么有什么办法可以最小化这个吗?

【问题讨论】:

标签: python string python-2.7 python-3.x


【解决方案1】:

这个问题是“经典”,但很多答案在 Python 3 中不起作用,因为 maketrans 函数已从 Python 3 中删除。符合 Python 3 的解决方案是:

使用string.punctuation 获取列表并使用str.translate 删除它们

import string
"hello, world !".translate({ord(k):"" for k in string.punctuation})

结果:

'hello world '

translate 的参数是(在 Python 3 中)一个字典。 Key是字符的ASCII码,value是替换字符。我使用字典理解创建了它。

【讨论】:

    【解决方案2】:

    您可以使用正则表达式从字符类替换为

    >>> import re
    >>> re.sub(r'[]!,:)([/-]', '', string)
    'Is this stack overflow'
    
    • []!,:)([/-] 匹配]!, 等的字符类。将其替换为''

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 1970-01-01
      • 2020-03-11
      • 2012-09-04
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多