簡體   English   中英

找出:給定句子中一個字符中出現了多少個單詞:PYTHON

[英]find out: In how many word a character is present in a given Sentence: PYTHON

在解釋我的要求之前,讓我解釋一下我不想要的東西:

s= 'Hello satya, have you achieved your goal'
s.count('l') #o/p: 3
#I don't want 3 instead  I need 2. How? explained below.

預期產量:

{'H':3, 'e':3, 'l':2, 'o':4, 's':1, 'a':3....etc}

也就是說:從該句子中選取所有唯一的字母/字符。 然后找到“該字符出現在多少個單詞中”,因此算不出出現次數並存儲在字典中。

例如,字符“ l”在該句子中出現3次,但在2個單詞中出現(打招呼時重復出現,但我希望將其計為1)。

請提出建議。 如果我錯過了一些使我的問題更容易理解的東西,請強調。

這是我嘗試過的:

def char_word(s):
    s_d = {}
    chars = list(s.replace(' ', ''))
    print(chars)
    for char in chars:
        c_count = 0
        for word in s.split():
            if char in word:
                c_count += 1
            s_d[char] = c_count
    print(s_d)
    return s_d

你可以做

sum(['l' in i for i in s.split()])

s.split()將句子拆分為單詞(按 )。 然后,for循環將檢查字符l是否在該特定單詞中,如果不是,則得出TrueFalse sum函數對所有True計數

首先,將字符串拆分為單個單詞,然后創建輸出字典。 我建議使用collections.Counter c.ass,它只是一個dict子類,旨在計算出現次數:

import collections
counter = collections.Counter()
words = s.split()

現在遍歷所有單詞,並從每個單詞創建一個set 由於set不能有重復的值,因此可以保證每個字符只有一個副本:

for word in words:
    characters = set(word)

最后,遍歷單詞的現在唯一的字符,增加該字符的計數器值:

    for character in characters:
        counter[character] += 1

另外,您可以將其縮短很多,甚至可以縮短為一線:

>>> counter = collections.Counter(c for word in s.split() for c in set(word))

要獲取特定字符的計數,只需通過counter[c]訪問即可:

>>> counter['l']
2
>>> counter['x']
0
>>> counter['H']
1

你可以這樣做,太,內groupbyitertools模塊和dict comprenesion像這樣:

from itertools import groupby

a = 'Hello satya, have you achieved your goal'
a = a.replace(',','').split()
sub = [j.lower() for k in a for j in set(k)]
final = {k:len(list(v)) for k,v in groupby(sorted(sub), lambda x: x)}
print(final)

Outut:

{'h': 3, 'u': 2, 's': 1, 'i': 1, 'c': 1, 'a': 4, 'd': 1, 'e': 3, 't': 1, 'v': 2, 'l': 2, 'o': 4, 'r': 1, 'g': 1, 'y': 3}

暫無
暫無

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

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