简体   繁体   English

Python:遍历字符串并仅打印特定单词

[英]Python: Iterate through string and print only specific words

I'm taking a class in python and now I'm struggling to complete one of the tasks. 我正在用python上课,现在正在努力完成其中一项任务。

The aim is to ask for an input, integrate through that string and print only words that start with letters > g. 目的是要求输入,通过该字符串进行集成,并且仅打印以字母> g开头的单词。 If the word starts with a letter larger than g, we print that word. 如果单词以大于g的字母开头,我们将打印该单词。 Otherwise, we empty the word and iterate through the next word(s) in the string to do the same check. 否则,我们清空单词并遍历字符串中的下一个单词以进行相同的检查。

This is the code I have, and the output. 这是我的代码以及输出。 Would be grateful for some tips on how to solve the problem. 对于解决问题的一些技巧将不胜感激。

        # [] create words after "G" following the Assignment requirements use of functions, menhods and kwyowrds
        # sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC)
        # [] copy and paste in edX assignment page

        quote = input("Enter a sentence: ")
        word = ""

        # iterate through each character in quote
        for char in quote:

            # test if character is alpha
            if char.isalpha():
                word += char 

            else:


                if word[0].lower() >= "h":
                    print(word.upper())   

                else:
                    word=""

    Enter a sentence: Wheresoever you go, go with all your heart
    WHERESOEVER
    WHERESOEVERYOU
    WHERESOEVERYOUGO
    WHERESOEVERYOUGO
    WHERESOEVERYOUGOGO
    WHERESOEVERYOUGOGOWITH
    WHERESOEVERYOUGOGOWITHALL
    WHERESOEVERYOUGOGOWITHALLYOUR



The output should look like,

Sample output:
WHERESOEVER
YOU
WITH
YOUR
HEART

Simply a list comprehension with split will do: 只需使用split进行列表理解即可:

s = "Wheresoever you go, go with all your heart"
print(' '.join([word for word in s.split() if word[0].lower() > 'g']))
# Wheresoever you with your heart

Modifying to match with the desired output (Making all uppercase and on new lines): 进行修改以与所需的输出匹配(使所有大写字母和换行符都生效):

s = "Wheresoever you go, go with all your heart"
print('\n'.join([word.upper() for word in s.split() if word[0].lower() > 'g']))

'''
WHERESOEVER 
YOU 
WITH 
YOUR 
HEART
'''

Without list comprehension: 没有列表理解:

s = "Wheresoever you go, go with all your heart"
for word in s.split():  # Split the sentence into words and iterate through each.
    if word[0].lower() > 'g':  # Check if the first character (lowercased) > g.
        print(word.upper())  # If so, print the word all capitalised.
s = "Wheresoever you go, go with all your heart"
out = s.translate(str.maketrans(string.punctuation, " "*len(string.punctuation)))
desired_result = [word.upper() for word in out.split() if word and word[0].lower() > 'g']
print(*desired_result, sep="\n")

Here is a readable and commented solution. 这是一个易于阅读和评论的解决方案。 The idea is first to split the sentence into a list of words using re.findall (regex package) and iterate through this list, instead of iterating on each character as you did. 这个想法首先是使用re.findall (正则表达式包)将句子拆分成单词列表,然后遍历该列表,而不是像您那样遍历每个字符。 It is then quite easy to print only the words starting by a letter greater then 'g': 这样就很容易只打印以大于“ g”的字母开头的单词:

import re

# Prompt for an input sentence
quote = input("Enter a sentence: ")

# Split the sentence into a list of words
words = re.findall(r'\w+', quote)

# Iterate through each word
for word in words:
    # Print the word if its 1st letter is greater than 'g'
    if word[0].lower() > 'g':
        print(word.upper())

To go further, here is also the one-line style solution based on exactly the same logic, using list comprehension: 更进一步,这也是使用列表理解基于完全相同的逻辑的单行样式解决方案:

import re

# Prompt for an input sentence
quote = input("Enter a sentence: ")

# Print each word starting by a letter greater than 'g', in upper case
print(*[word.upper() for word in re.findall(r'\w+', quote) if word[0].lower() > 'g'], sep='\n')

Your problem is that you're only resetting word to an empty string in the else clause. 您的问题是,您仅要将else子句中的word重置为空字符串。 You need to reset it to an empty string immediately after the print(word.upper()) statement as well for the code as you've wrote it to work correctly. 您需要在print(word.upper())语句之后立即将其重置为空字符串,以确保代码正确运行。

That being said, if it's not explicitly disallowed for the class you're taking, you should look into string methods, specifically string.split() 话虽这么说,如果您使用的类没有明确禁止使用,则应该研究字符串方法,特别是string.split()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM