文字列内の行に文字が何回表示されるかを示すリストを Python で文字列から作成したいと考えています。例えば:
my_string= "google"
次のようなリストを作成したいと思います。
[['g', 1], ['o', 2], ['g', 1], ['l', 1], ['e', 1]]
ありがとう!
正規表現と辞書を使用して、このように各文字の最長の文字列を見つけて保存できます
s = 'google'
nodubs = [s[0]] + [s[x] if s[x-1] != s[x] else '' for x in range(1,len(s))]
nodubs = ''.join(nodubs)
import re
dic = {}
for letter in set(s):
matches = re.findall('%s+' % letter, s)
longest = max([len(x) for x in matches])
dic[letter] = longest
print [[n,dic[n]] for n in nodubs]
結果:
[['g', 1], ['o', 2], ['g', 1], ['l', 1], ['e', 1]]