正則運算式和文本資料新手在這里。
我有一個術語串列,我想獲得串列中的字串出現在單獨字串中的總時間的總和。在下面的示例中,字母“o”在我的字串中出現了 3 次,而字母“b”出現了 2 次。我創建了一個名為 allcount 的變數,我知道它不起作用,但理想情況下總和為 5。
任何幫助表示贊賞。
import re
mylist = ['o', 'b']
my_string = 'Bob is cool'
onecount = len(re.findall('o', my_string)) #this works
#allcount = sum(len(re.findall(mylist, my_string))) #this doesn't work
uj5u.com熱心網友回復:
構建Counter和迭代串列元素會更容易和更有效:
from collections import Counter
c = Counter(my_string.lower())
# Counter({'b': 2, 'o': 3, ' ': 2, 'i': 1, 's': 1, 'c': 1, 'l': 1})
[c[s] for s in mylist]
# [3, 2]
uj5u.com熱心網友回復:
你必須在你的字串中找到不同的模式。
這可以通過使用管道來完成| 符號
import re
mylist = ['o', 'b']
my_string = 'Bob is cool'
onecount = len(re.findall("o|b|B", my_string)) #this works
print(onecount)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/520763.html
