首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >python 3.3将句子转换为位置

python 3.3将句子转换为位置
EN

Stack Overflow用户
提问于 2016-01-11 04:19:48
回答 1查看 448关注 0票数 0

我需要这组代码能够将句子/句子2/句子3转换为三个位置,作为每个句子的单独列表,最好使用与我尝试过的方法类似的方法。所以输出应该是这样的:

1、2、3、4、5、6、7、8、9、1、3、8、9、5、6、7、4

1、2、3、4、5、6、7、3、4

1、2、3、4、5、6、7、8、5、1、11、12、13、14、8

代码语言:javascript
运行
复制
sentence = ("ask not what you can do for your country ask what your country can do for you")
sentence2 = ("some people enjoy computing others do not enjoy computing")
sentence3 = ("i will use this as my last sentence as i do not need another sentence")

d = {}
i = 0
values = []
for i, word in enumerate(sentence, sentence2, sentence3(" ")):
    if not word in d:
        d[word] = (i + 1)
    values += [d[word]]
print(values)
EN

回答 1

Stack Overflow用户

发布于 2016-01-11 05:22:48

这就解决了这个问题

代码语言:javascript
运行
复制
def conv2pos(*sentences):
    def conv_one(s):
        words = s.split()
        word_pos = {w:words.index(w) for w in set(words)}
        return [word_pos[w]+1 for w in words]

    return [conv_one(s) for s in sentences]

print(conv2pos(sentence, sentence2, sentence3))

对于给定的句子,它会产生

代码语言:javascript
运行
复制
[
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 8, 9, 5, 6, 7, 4],
 [1, 2, 3, 4, 5, 6, 7, 3, 4],
 [1, 2, 3, 4, 5, 6, 7, 8, 5, 1, 11, 12, 13, 14, 8]
]

基本上,对于提供的每个句子,它将句子拆分成单词(在空格上)。

然后,它创建一个字典,为每个唯一的单词映射一个单词在句子中的第一个位置。

然后,它根据这样的字典创建每个单词在句子中的位置的列表。

注意:字典是可选的。它用于缓存每个单词的位置,并避免扫描列表中已经遇到的单词。如果我们想要删除它,我们可以这样做

代码语言:javascript
运行
复制
def conv2pos(*sentences):
    def conv_one(s):
        words = s.split()
        return [words.index(w)+1 for w in words]

    return [conv_one(s) for s in sentences]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34710342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档