【问题标题】:How to extract first letter of every nth word in a sentence?如何提取句子中第 n 个单词的首字母?
【发布时间】:2022-01-21 17:11:45
【问题描述】:

我试图提取每 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")

【问题讨论】:

  • 你可以只取字符串的第 0 个元素,比如 word[0]
  • 顺便说一句,对于你所坚持的任务,已经有几十个类似的问题了。谷歌python split extract first letter of every word in string.

标签: python function split extract


【解决方案1】:

正如评论指出的那样,将其拆分,然后只访问第一个字符:

def extract(text):
    for word in text.split(" "):
        print(word[0])

text.split(" ") 返回一个数组,我们正在循环该数组。 word 是该数组中的当前条目 (string)。现在,在 python 中,您可以使用典型的数组表示法访问字符串的第一个字符。因此,word[0] 返回该单词的第一个字符,word[-1] 将返回该单词的最后一个字符。

【讨论】:

  • 我可能是个笨蛋,但是当你做 word[0] 时,为什么你会得到每个单词的第一个字母,而不是例如整个第一个单词,甚至只有第一个字母第一个字。
  • 欢迎来到 StackOverflow。支持对您有帮助的问题或答案。我已经编辑了我的答案以包含更多细节。如果您刚刚开始使用 python,请参阅此链接以获取更多信息:pythonbasics.org/strings
  • @AmalJaimon 这是因为 word 是一个在 .split 创建的列表中移动的元素,而不是整个句子变量(文本)
【解决方案2】:

不知道第一部分是怎么解决的,第二部分解决不了,
但无论如何,python中的字符串只是一个字符列表,所以如果你想访问第一个字符,你会得到第0个索引。因此,将其应用于您的示例,正​​如您输入的评论所提到的(word[0]),

所以您可以打印单词 [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")

【讨论】:

    【解决方案3】:

    以下代码可能会对您有所帮助。只是基于您所说的一个示例想法。

     #
     # 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"
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      相关资源
      最近更新 更多