【问题标题】:Finding specific characters within a list在列表中查找特定字符
【发布时间】:2020-02-25 02:26:58
【问题描述】:

目标是从用户的段落中创建一个列表并进行迭代,以便我可以计算有多少单词包含特殊字母“j,x,q,z”。

示例输入:
在地下的一个洞里,住着一个霍比特人。不是一个肮脏、肮脏、潮湿、满是虫子末端和渗出气味的肮脏、肮脏、潮湿的洞,也不是一个干燥、裸露、沙质的洞,里面没有东西可以坐下或吃东西;这是一个霍比特人洞,这意味着舒适。

示例输出: 1 个带有稀有字符的单词

我已经开始编写代码,将用户的段落分成一个列表,但我很难遍历列表并找到特殊字母的每个实例。

这是我目前所拥有的:

def rareChar(words):
    rareWords = 0
    rareChars = ['j', 'x', 'q', 'z']
    for astring in words:
        wds = words.split()
        for char in wds:
            if char in rareChars:
                rareWords = rareWords + 1
    return rareWords

def CoolPara(words):
    print(rareChar(words), 'word(s) with a rare character')

    # DO NOT CHANGE CODE BELOW

    print(CoolPara(input("Enter: ")))

如果我使用示例输入运行,我会得到“0 个带有稀有字符的单词”的输出。我该如何解决这个问题才能获得预期的输出。任何帮助将不胜感激,因为我对编码还比较陌生

还有一个简短的说明:我只被允许使用 split() 和 Len() 的方法/函数

【问题讨论】:

  • .index 应该做的工作
  • 您应该遍历输出并添加一些打印语句以确保满足语句和条件。
  • 错字。内循环上面的行不应该是 wds = astring.split()
  • for astring in words:的目的是什么?
  • 从变量名来看,我觉得你很困惑。将“for astring in words:”更改为“for word in words.split():”。然后将“for char in wds:”改为for char in word:”。然后删除“wds = words.split()”。

标签: python python-3.x


【解决方案1】:

也许这是一个向您介绍一些 python 功能的机会:

from typing import List


def rare_char(sentence: str, rare_chars: List[str]=["j", "x", "q", "z"]) -> List[str]:
    return [word for word in sentence.split() if 
            any(char in word for char in rare_chars)]


def cool_para(sentence: str) -> str:
    return f"{len(rare_char(sentence))} word(s) with rare characters"

这个答案使用:

  1. typing,可供第三方工具使用,例如类型检查器、IDE、linter,但更重要的是让其他可能正在阅读您的代码的人清楚您的意图。
  2. default arguments,而不是在函数中硬编码它们。记录您的函数非常重要,这样用户就不会对结果感到惊讶(请参阅Principle of Least Astonishment)。当然,还有其他方法可以记录您的代码(请参阅 docstrings)和设计该界面的其他方法(例如 class),但这只是为了说明这一点。
  3. List comprehensions,它可以通过使代码更多 declarative instead of imperative 来使您的代码更具可读性。很难确定命令式算法背后的意图。
  4. string interpolation,根据我的经验,它比连接更不容易出错。
  5. 我使用 pep8 样式指南来命名函数,这是 Python 世界中最常见的约定。
  6. 最后,我在cool_para 函数中返回了str 而不是打印,因为# DO NOT CHANGE CODE BELOW 注释下方的代码正在打印函数调用的结果。

【讨论】:

  • 迄今为止我见过的最好的实现之一。不能更 Pythonic。 :-) 我只是将rare_chars() 重命名为find_rare_words()
【解决方案2】:

理想情况下,您想使用列表推导。

def CoolPara(letters):
  new = [i for i in text.split()]
  found = [i for i in new if letters in i]
  print(new) # Optional
  print('Word Count: ', len(new), '\nSpecial letter words: ', found, '\nOccurences: ', len(found))

CoolPara('f') # Pass your special characters through here

这给了你:

['In', 'a', 'hole', 'in', 'the', 'ground', 'there', 'lived', 'a', 'hobbit.', 'Not',
 'a', 'nasty,', 'dirty,', 'wet', 'hole,', 'filled', 'with', 'the', 'ends', 'of',
'worms', 'and', 'an', 'oozy', 'smell,', 'no', 'yet', 'a', 'dry,', 'bare,', 'sandy',
'hole', 'with', 'nothing', 'in', 'it', 'to', 'sit', 'down', 'on', 'or', 'to', 'eat;',
'it', 'was', 'a', 'hobbit-hole,', 'and', 'that', 'means', 'comfort']
Word Count:  52
Special letter words:  ['filled', 'of', 'comfort']
Occurences:  3

【讨论】:

    【解决方案3】:
    def rareChar(words):
    rareWords = 0
    rareChars = ['j', 'x', 'q', 'z']
    
    #Split paragraph into words
    words.split()
    for word in words:
        #Split words into characters
        chars = word.split()
        for char in chars:
            if char in rareChars:
                rareWords = rareWords + 1
    return rareWords
    
    def CoolPara(words):
        #return value rather than printing
        return '{} word(s) with a rare character'.format(rareChar(words))
    
    
    # DO NOT CHANGE CODE BELOW
    
    print(CoolPara(input("Enter: ")))
    

    输入:你好,这是一个关于动物园的句子

    输出:1 个带有稀有字符的单词

    【讨论】:

      【解决方案4】:

      以下代码是您的编辑,导致1的正确答案

      def main():
      
          def rareChar(words):
              rareWords = 0
              rareChars = ['j', 'x', 'q', 'z']
      
              all_words = list(words.split())
      
              for a_word in all_words:
                  for char in a_word:
                      if char in rareChars:
                          rareWords = rareWords + 1
              return rareWords
      
          def CoolPara(words):
              print(rareChar(words), 'word(s) with a rare character')
      
      
          # DO NOT CHANGE CODE BELOW
      
          print(CoolPara(input("Enter: ")))
      
      main()
      

      答案:

      C:\Users\Jerry\Desktop>python Scraper.py
      Enter: In a hole in the ground there lived a hobbit. Not a nasty, dirty, wet hole, filled with the ends of worms and an oozy smell, no yet a dry, bare, sandy hole with nothing in it to sit down on or to eat; it was a hobbit-hole, and that means comfort.
      
      1 word(s) with a rare character
      

      【讨论】:

        【解决方案5】:

        此代码适用于您。把输入的单词去掉注释,把我用来测试代码的单词字符串语句注释掉。

        para 方法不需要。

        def rareChar(words):
            rareWords = 0
            rareChars = ['j', 'x', 'q', 'z']
            for word in words:
                wds = word.split()
                for char in wds:
                    if char in rareChars:
                        rareWords = rareWords + 1
            return rareWords
        
        words = 'john xray quebec zulu'
        # words = (input("Enter: "))
        
        x = rareChar(words)
        print(f"There are {x} word(s) with a rare character")
        

        【讨论】:

          【解决方案6】:

          Barb 提供的解决方案适用于单个字母:

          CoolPara('f')

          但它不适用于原始海报所要求的多个字符。例如这不会返回正确的结果:

          CoolPara("jxqz")

          这是 Barb 解决方案的略微改进版本:

          def CoolPara(letters):
              new = [i for i in text.split()]
              found = list()
              for i in new:
                  for x in i:
                      for l in letters:
                          if x == l:
                              found.append(i)
              print("Special letter words: ", found)
              print("word(s) with rare characters ", len(found))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多