我試圖提取每 5 個單詞的第一個字母,經過一些研究,我能夠弄清楚如何獲得每 5 個單詞。但是,我怎么知道提取每第 5 個單詞的第一個字母并將它們放在一起組成一個單詞。這是我到目前為止的進展:
def extract(text):
for word in text.split()[::5]:
print(word)
extract("I like to jump on trees when I am bored")
uj5u.com熱心網友回復:
正如評論指出的那樣,拆分它,然后只訪問第一個字符:
def extract(text):
for word in text.split(" "):
print(word[0])
text.split(" ")回傳一個陣列,我們正在遍歷該陣列。word是該string陣列中的當前條目 ( )。現在,在 python 中,您可以以典型的陣串列示法訪問字串的第一個字符。因此,word[0]回傳該單詞的第一個字符,word[-1]將回傳該單詞的最后一個字符。
uj5u.com熱心網友回復:
我不知道你是如何解決第一部分而無法解決第二部分的,
但無論如何,python中的字串只是一個字串列,所以如果你想訪問第一個字符,你會得到第0個索引。所以將它應用到你的例子中,正如你提到的評論你輸入的 (word[0]),
所以你可以列印 word[0] 或者收集串列中的第一個字符來做任何進一步的操作(我相信你想要做的,不僅僅是列印它們!)
def extract(text):
mychars=[]
for word in text.split()[::5]:
mychars.append(word[0])
print(mychars)
extract("I like to jump on trees when I am bored")
uj5u.com熱心網友回復:
下面的代碼可能會幫助你。只是基于您所說的示例想法。
#
# str Text : A string of words, such as a sentence.
# int split : Split the string every nth word
# int maxLen : Max number of chars extracted from beginning of each word
#
def extract(text,split,maxLen):
newWord = ""
# Every nth word
for word in text.split()[::split]:
if len(word) < maxLen:
newWord = word[0:] #Entire word (if maxLength is small)
else:
newWord = word[:maxLen] #Beginning of word until nth letter
return (None if newWord=="" else newWord)
text = "The quick brown fox jumps over the lazy dog."
result = extract(text, split=5, maxLen=2) #Use split=5, maxLen=1 to do what you said specifically
if (result):
print (result) #Expected output: "Thov"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/387362.html
