[英]How to change words in a list to upper/lower case using range - Python
[英]Python: How to find a letter in a sentence's list of words and return those words in their original case (upper/lower)
我正在嘗試創建一個 Python function ,它接受一個句子,將其轉換為一個列表,並確定給定字母是否出現在該列表中的任何單詞中,無論字母大小寫如何。 我希望 function 然后只返回一個包含該字母的單詞的列表,每個單詞的字母都是原始大小寫。
我已經能夠返回這些單詞,但現在所有字母都是小寫的,即使它們最初是大寫的。 如何在原始情況下返回帶有字母的單詞?
我寫的:
def word_with(word, char):
char_lower = char.lower()
word_lower = word.lower()
word_string = word_lower.split()
word_with = [x for x in word_string if char_lower in x]
return word_with
當我測試時:
word = "她在海邊賣貝殼"
打印(word_with(單詞,“s”))
output 是:
['她','賣','貝殼','海濱']
但我希望“她”有一個大寫的“S”,就像它在原版中出現的那樣。 我該怎么做呢? 謝謝。
如果您將.lower()
調用移至列表理解的條件部分,則可以返回原始單詞。
像這樣的東西:
def words_with(s, char):
char_lower = char.lower()
# Get individual words
words = s.split()
# Return all words that contain char
return [word for word in words if char_lower in word.lower()]
您的不起作用,因為您在檢查之前將單詞小寫。 在檢查它是否在單詞中時執行此操作,如下所示:
def word_with(sent, letter):
x = [word for word in sent.split() if letter in word.lower()]
return x
用這個:
[x for x in word_string if char_lower in x.lower()]
def word_with(word, char):
char_lower = char.lower()
word_string = word.split()
word_with = [x for x in word_string if char_lower in x.lower()]
return(word_with)
word = "She sells seashells by the seashore"
print(word_with(word, "s"))
['She', 'sells', 'seashells', 'seashore']
不要對字符串執行任何轉換,並在生成器中使用正則表達式而不是in
關鍵字:
def word_with(word, char):
return [x for x in word.split() if re.search(char, x, re.IGNORECASE)]
應該做的伎倆。
我會嘗試拆分,然后根據您從列表理解中獲得的索引返回小寫字母並返回這些單詞。
def word_with(word, char):
char_lower = char.lower()<br/>
original_split = word.split()
word_lower = word.lower()<br/>
word_string = word_lower.split()<br/>
word_with = [x for x in range(len(word_string)) if char_lower in word_string[i]]<br/>
return([original_split[i] for i in word_with])
我們可以使用正則表達式來做到這一點:請檢查您是否使用此代碼獲得了所需的 output
import re
def word_with(word, char):
word_string = word.split()
print(word_string)
word_with = [x for x in word_string if re.search(r'^[s]',x,re.I)]
return(word_with)
word = "She sells seashells by the seashore"
print(word_with(word,'s'))
這將返回與字符匹配的字母中的原始單詞
def word_with(word, char):
return [x for x in word.split() if char.lower() in x.lower()]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.