【问题标题】:receives a string and return with only english words接收一个字符串并仅返回英文单词
【发布时间】:2021-07-23 03:55:06
【问题描述】:

这是我的代码

def words_only(sentence):
    wordlist1 = sentence.split()
    wordlist2 = []
    for word in wordlist1:
        modified = ''
        for char in word:
            if char in '_-!,.?":;0123456789':
                char = ''
            modified += char
        wordlist2.append(modified)
    return wordlist2

描述是:words_only 接收一个字符串作为参数,并返回一个包含句子中所有单词的列表。出于此功能的目的,单词是仅由字母组成的序列(小写或大写 输入是

words_only("two-fold will count as 2 words.")

但是,我上次测试失败了。我的输出是

['twofold', 'will', 'count', 'as', '', 'words']

正确的输出应该是

["two", "fold", "will", "count", "as", "words"]

我怎样才能修复我的代码,使冒号消失并且“双倍”将计为 2 个单词?并且还有一个空字符串导致了错误。

【问题讨论】:

  • 请在此处粘贴代码
  • edit问题并粘贴代码

标签: python python-3.x string list


【解决方案1】:

问题是,当您有一个仅由列表中的符号/数字组成的单词时,它会给您一个空字符串,在您的输出图像中,您似乎不应该将此空字符串添加到您的最终名单。您可以通过在 wordlist2.append(modified_w) 之前添加 if 语句来修复它。

写: 如果修改_w: wordlist2.append(modified_w)

空字符串被认为是假的,所以它不会添加它,而如果符号/数字在一个单词中,它会将它从单词中删除,然后添加更正的单词

【讨论】:

    【解决方案2】:

    在使用 Python 时,您应该尽可能地利用它的特性——即列表解析和内置函数:

    [word for word in sentence.split() if word.isalpha()]
    

    【讨论】:

      【解决方案3】:

      会发生这种情况是因为你没有分割结束str'-'的单词

      您可以更改代码

      def words_only(sentence):
          wordlist1 = sentence.split()
          wordlist2 = []
          for word in wordlist1:
              modified = ''
              for char in word:
                  if char in '-_0123456789,.[];{}':
                      if modified: wordlist2.append(modified)
                      modified = ''
                  else:
                      modified += char
      
              if modified: wordlist2.append(modified)
          return wordlist2
      

      希望这会有所帮助!

      【讨论】:

      • 你搞错了。 char == '_-.123456789'应该是char in '_-.123456789',一个字符怎么可能等于呢?它总是假的
      • 你能告诉我这条线是什么意思吗? “如果修改:word_list2.append(modified)”
      • 好吧,它至少对我有用,我已经发布了我的代码和结果,'如果修改 word_list2.append(modified)' 表示如果修改的值不为空也不为无,则添加该值到 word_list2。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多