简体   繁体   English

如何使用Python仅显示带有元音的单词中的字母

[英]How to use Python to show only the letters from words with vowels

VOWELS = "aeiou"

word = "matt"
word = "james is funny"
cnt = 0

for v1 in VOWELS:
    print ("vowel", cnt)
    print("letter:", v1)
    cnt = cnt + 1
    for v1 in word:
        print ("location in string", cnt)
        print("letter:", v1)
        cnt = cnt + 1

I've been trying to figure this out for hours and it's driving me crazy. 我已经尝试了好几个小时了,这让我发疯。 I just need python to print only the vowel letters in the words. 我只需要python在单词中仅打印元音字母。

import re

word = "james is funny"
print re.sub('[^aeiou]','',word)

OUTPUT:

'aeiu'

Print only the vowel letters in the words: 仅打印单词中的元音字母:

print ''.join(c for c in text if c in 'aeiou')

Print only words containing vowels: 仅打印包含元音的单词:

words = text.split()
def containsVowel(word):
    any(c in word for c in 'aeiou')
words_with_vowels = [w for w in words if containsVowels(w)]
print words_with_vowels

The straightforward way: 简单的方法:

  • for each letter in the text 对于文本中的每个字母
    • if it is a vowel, print it 如果是元音,请打印
    • otherwise print a space 否则打印一个空格

Translates directly into Python (along with a tweak to keep everything on the same line when printing): 直接转换为Python(并进行调整以在打印时将所有内容保持在同一行):

VOWELS = "aeiou"

word = "james is funny"

for letter in word:
    if letter in VOWELS:
        print(letter, end='')
    else:
        print(' ', end='')

Or the slightly more fancy way: 或者更花哨的方式:

  • Replace all non-vowels with spaces. 用空格替换所有非元音。 Print the result 打印结果

Using the regular expression pattern language: 使用正则表达式模式语言:

import re

word = "james is funny"

new_word = re.sub('[^aeiou]', ' ', 'james is funny')

print new_word
vowels = "aeiou"
word = "james is funny and really fun!"
for v1 in range(len(vowels)):
    for v2 in range (len(word)):
        if vowels[v1] == word[v2]:
            print("location in string", v2)
            print("letter:", vowels[v1])

Python has a built in function which allows you to use strings as list and by using this you are able to loop through each letter of the string and compare with the vowels. Python具有内置函数,可让您将字符串用作列表,并使用它可以遍历字符串的每个字母并与元音进行比较。

Eg 例如

vowels[0] = a
word[10] = u

We need to find out the vowel from the word. 我们需要从单词中找出元音。 Here passing the word to re.findall() , it will find all the vowels in the word and return as list of characters. 在这里将word传递给re.findall() ,它将找到单词中的所有元音并作为字符列表返回。 We are joining the list to display as word. 我们正在加入列表以显示为单词。

import re
word = "james is funny"
k = re.findall(r'[aeiou]', word)
print ''.join(k)

Out: 'aeiu'

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

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