【问题标题】:small issue with whitespeace/punctuation in python?python中空白/标点符号的小问题?
【发布时间】:2011-06-05 02:40:20
【问题描述】:

我有这个功能可以将文本语言转换成英文:

def translate(string):
    textDict={'y':'why', 'r':'are', "l8":'late', 'u':'you', 'gtg':'got to go',
        'lol': 'laugh out    loud', 'ur': 'your',}
    translatestring = ''
    for word in string.split(' '):
        if word in textDict:
            translatestring = translatestring + textDict[word]
        else:
            translatestring = translatestring + word
    return translatestring

但是,如果我想翻译y u l8?,它将返回whyyoul8?。当我返回它们时,我将如何分隔单词,以及如何处理标点符号?任何帮助表示赞赏!

【问题讨论】:

  • @Wobble,抱歉,我没有收到编辑冲突的通知...

标签: python punctuation


【解决方案1】:

单行理解:

''.join(textDict.get(word, word) for word in re.findall('\w+|\W+', string))

[编辑] 修正正则表达式。

【讨论】:

  • @icktoofay 为什么代码太多?这就像[f(x) for x in seq]
  • 我意识到了这一点,但我只是认为原始代码更清晰。
  • @icktoofay dict.get 方法比if x in dict: ... else: ...好多了
【解决方案2】:

您正在将单词添加到没有空格的字符串中。如果您打算以这种方式做事(而不是您在上一个关于此主题的问题中建议的方式),您需要手动重新添加空格,因为您拆分它们。

【讨论】:

    【解决方案3】:

    "y u l8" 在 " " 上拆分,给出 ["y", "u", "l8"]。替换后,你得到 ["why", "you", "late"] - 你在不添加空格的情况下连接它们,所以你得到 "whyyoulate"。 if 的两个分支都应该插入一个空格。

    【讨论】:

      【解决方案4】:

      您只需添加+ ' ' + 即可添加空格。但是,我认为您要做的是:

      import re
      
      def translate_string(str):
          textDict={'y':'why', 'r':'are', "l8":'late', 'u':'you', 'gtg':'got to go',  'lol': 'laugh out loud', 'ur': 'your',}
          translatestring = ''
          for word in re.split('([^\w])*', str):
              if word in textDict:
                  translatestring += textDict[word]
              else:
                  translatestring += word
      
          return translatestring
      
      
      print translate_string('y u l8?')
      

      这将打印:

      why you late?
      

      此代码更优雅地处理问号之类的内容,并保留输入字符串中的空格和其他字符,同时保留您的原始意图。

      【讨论】:

      • 谢谢!只是为了澄清, '([^\w])*' 到底是做什么的?
      【解决方案5】:

      我想建议以下替换此循环:

      for word in string.split(' '):
          if word in textDict:
              translatestring = translatestring + textDict[word]
          else:
              translatestring = translatestring + word
      

      对于 string.split(' ') 中的单词: translatetring += textDict.get(word, word)

      dict.get(foo, default) 将在字典中查找 foo,如果尚未定义 foo,则使用 default

      (运行时间,现在简短说明:拆分时,您可以根据标点符号和空格进行拆分,保存标点符号或空格,并在加入输出字符串时重新引入。这需要更多的工作,但它会完成工作。)

      【讨论】:

        猜你喜欢
        • 2011-04-08
        • 2017-02-04
        • 1970-01-01
        • 2022-06-11
        • 2020-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多