如何解决在PythonPandas或Pyspark中创建单词及其位置
嗨,我正在尝试创建一个字符串,该字符串将具有单词及其在输入字符串中出现的位置。我试过了-
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
这里需要注意三件事
- 索引t从1开始而不是0
- 删除字典的{},仅输入一个字符串
- 如果这个单词在重复,那么我提到的所有位置都用逗号隔开
如何获得所需的输出。请帮忙
解决方法
使用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"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。