因此,对于我的python项目的第二部分,我们必须识别句子中的单个单词,将它们存储在列表中,并将每个单词替换为列表中单词的位置。以下是我到目前为止的情况:
s = 'I am having a very nice day.'
split = s.split()
print(split)
len(s.split())
答案 0 :(得分:3)
这是你想要的吗?
s = 'I am having a very nice day.'
words = s.split()
res = list(range(len(words)))
print(res) # [0, 1, 2, 3, 4, 5, 6]
答案 1 :(得分:2)
您可以尝试:
s = 'I am having a very nice day.'
sp_s = s.split()
l = [sp_s.index(x) for x in sp_s]
l
中的输出是:
[0, 1, 2, 3, 4, 5, 6]
答案 2 :(得分:2)
第一个解决方案:
>>> map(lambda x: s.split().index(x), s.split())
[0, 1, 2, 3, 4, 5, 6]
第二个解决方案:
>>> range(len(s.split()))
[0, 1, 2, 3, 4, 5, 6]
答案 3 :(得分:0)
只需打印split
列表的长度范围即可。这将为您提供所有数字的长度。
s = 'I am having a very nice day.'
print(range(len(s.split())))
# [0, 1, 2, 3, 4, 5, 6]
答案 4 :(得分:0)
import re
s = "I am having a very nice day."
words = list(set(re.findall(r'\w+', s)))
print words
s2 = re.sub(r'\w+', lambda m: str(words.index(m.group(0))), s)
print s2
输出:
['a', 'I', 'am', 'day', 'very', 'having', 'nice']
1 2 5 0 4 6 3.
答案 5 :(得分:0)
如果您不想为重复单词创建新索引:
>>> d = dict()
>>> for word in "the cat in the hat".split():
>>> if word not in d:
>>> d[word] = len(d)
>>> [word[0] for word in sorted(d.iteritems(), key=lambda x: x[1])]
['the', 'cat', 'in', 'hat']
>>>> [d[word] for word in "the cat in the hat".split()]
[0, 1, 2, 0, 3]
答案 6 :(得分:0)
这是一个更接近原始尝试的人。这应该与重复一起使用并使用原始数组。
method(:greet).owner
# => Object