如何让我的代码分析句子,然后列出在文本fi上的位置

2024-10-02 02:30:49 发布

您现在位置:Python中文网/ 问答频道 /正文

到目前为止我已经拿到了这个

UserSen = input("Enter a sentence of your choice, ")
position = {} # word -> position
words = UserSen.split()
for word in words:
    if word not in position: # new word
        position[word] = len(position) + 1 # store its position

我想把它写出来,比如说,如果你在句子“你好你好你好你好吗”,它会输出1,2,3,4,1,3,4,1


Tags: ofinforinputyourifnotposition
1条回答
网友
1楼 · 发布于 2024-10-02 02:30:49

非常简单,您需要在目前找到的位置内保存一个列表:

# UserSen = "HI HOW ARE YOU HI ARE YOU HI"
UserSen = input("Enter a sentence of your choice, ")

# word -> positionDictionary
positionDictionary = {}
positionList       = []
words              = UserSen.split()

for word in words:

    # print( word )

    # new word
    if word not in positionDictionary:

        # store its positionDictionary
        positionDictionary[word] = len(positionDictionary) + 1

    positionList.append( positionDictionary[word] )

    # print( positionDictionary )
    # print( positionList )


print( positionList )

相关问题 更多 >

    热门问题