簡體   English   中英

根據空格查找字符串中的字符

[英]Finding characters in a string based on white spaces

所以我試圖讓函數工作,返回一個新的單個字符列表,緊跟其他兩個給定的字符。 像這樣:

def filter_possible_chars(corpus, last):
    """
    >>> filter_possible_chars('lazy languid line', 'la')
    ['z', 'n']
    >>> filter_possible_chars('pitter patter', 'tt')
    ['e', 'e']
    """
    char_list = []
    corpus_split = corpus.split()
    for word in corpus_split:
        if last in word:
            word_split = word.split(last)
            follows_last = word_split[1]
            char_list.append(follows_last[0])
    return char_list

此函數適用於docstring中給出的示例,但是我需要包含包含空格的示例,例如:

>>> filter_possible_chars('when the goat jumped to the rock', ' t')

它會回來:

['h', 'o', 'h']

但由於我的功能顯然是刪除了空格,我想我需要嘗試一種完全不同的方法。 我想過不將字符串拆分成單個單詞並嘗試使用給定的字母索引它,但我想不出一種方法可以使字符串中的多個實例工作。

>>> pat="tt"
>>> corpus="pitter patter"
>>> print(re.findall("%s(.)"%pat,corpus))
['e', 'e']
>>> corpus,pat = 'when the goat jumped to the rock', ' t'
>>> re.findall("%s(.)"%pat,corpus)
['h', 'o', 'h']
>>> corpus,pat = 'lazy languid line', 'la'
>>> re.findall("%s(.)"%pat,corpus)
['z', 'n']

說明

  • %字符串格式化運算符,因此例如"%s(.)" % "la"計算為"la(.)"

  • 正則表達式. 是“任何字符”的模式, ()定義可以在以后檢索其值的 ,例如使用findall

    如果模式中存在一個或多個組,則返回組列表

因此,例如,模式la(.)表示“搜索la后跟任何字符,並捕獲該字符”。

你的想法如何解決這個問題是完全沒問題的。 而不是將句子分成單詞,你應該嘗試在完整corpus找到last實例。 但是,嘿,實際上split功能可以為你做到這一點。

corpus = 'when the goat jumped to the rock'
spl = corpus.split(' t')
print spl
>> ['when', 'he goat jumped', 'o', 'he rock']
res = [x[0] for x in spl[1:] if len(x) > 0]
print res
>> ['h', 'o', 'h']

所以,你可以拆分corpuslast則擺脫分裂的結果,所有的字符串沒有第一個(因為它沒有以last ),然后得到每個這樣的字符串的第一個字母。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM