问题描述
嗨,我正在尝试创建一个字符串,该字符串将具有单词及其在输入字符串中出现的位置。我试过了-
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"