在列表中查找特定字符


11

目标是从用户的段落中列出并进行迭代,以便我可以计算出多少个单词包含特殊字母“ 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应该做的工作
— bigbounty 19-10-29

您应该遍历输出并添加一些打印语句,以确保满足语句和条件。
— Fallenreaper

错字。内循环上方的行不应该是wds = astring.split()
— abhilb

目的是for astring in words:什么?
— norok2

从变量名来看,我认为您很困惑。将“ for astring in words:”更改为“ for word in words.split():”。然后“在wds中使用char:”到在word中使用char :。并删除“ wds = words.split()”
— 。– kantal

Answers:


4

也许这是一个向您介绍一些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. 打字,这可以通过第三方工具,如类型检查,集成开发环境,棉短绒可以使用,但更重要的是让你的意图明显给其他人谁可能是阅读你的代码。
  2. 默认参数,而不是在函数内部对其进行硬编码。记录功能非常重要,这样用户就不会对结果感到惊讶(请参阅 “最少惊讶的原理”)。当然,还有其他方式来记录您的代码(请参阅docstrings)和其他方式来设计该接口(例如,可以是一个类),但这只是为了说明这一点。
  3. 列表理解,通过使代码更具声明性而不是命令性,可以使您的代码更具可读性。确定命令式算法背后的意图可能很困难。
  4. 字符串插值,根据我的经验,它比连接更容易出错。
  5. 我使用了pep8样式指南来命名函数,这是python世界中最常见的约定。
  6. 最后,不是打印,而是str在cool_para函数中返回a ,因为# DO NOT CHANGE CODE BELOW注释下方的代码正在打印函数调用的结果。

1
到目前为止,我所见过的最好的实现之一。再没有Pythonic了。:-)我只是改名rare_chars()为find_rare_words()。
— accdias

1

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

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

0
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个字(带罕见字符)


0

以下代码是对您的代码的修改,可以正确回答 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

0

该代码将为您服务。取消标记输入的单词,并标记出我用来测试代码的单词字符串语句。

不需要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")

0

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))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.