嗨,我正在尝试创建一个字符串,该字符串将具有单词及其在输入字符串中出现的位置。我试过了-
def wordPositions(s):
aDict = {}
words = s.split(' ')
for item in words:
position = words.index(item)
aDict[item] = position
return aDict
s = 'Create a string with position from a string a'
wp = wordPositions(s)
print(wp)
它的输出是
{'Create': 0, 'a': 1 'string': 2, 'with': 3, 'position': 4, 'from': 5}
但我希望我的输出是
'Create': 1, 'a': 2,7,9 'string': 3,8 'with': 4, 'position': 5, 'from': 6
这里有三件事需要注意
如何获得所需的输出。请帮忙
使用re
,defaultdict
您可能会实现想要做的事情:
from collections import defaultdict
import re
s = 'Create a string with position from a string a'
wp = defaultdict(list)
for n, k in enumerate(s.split()):
wp[k].append(n+1)
raw_output = re.search('{(.*)}', str(wp)).group(1).replace('[','').replace(']','')
final_output = re.sub("(\d), '", r"\1 '", raw_output)
输出:
"'Create': 1 'a': 2, 7, 9 'string': 3, 8 'with': 4 'position': 5 'from': 6"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句