|
|
发表于 2023-8-5 20:30:41
|
显示全部楼层
根据题目的要求,我们需要将字符串text中的每个单词与字符串列表words中的每个单词进行比较,并返回它们在text中的位置。
首先,我们可以使用split()函数将text字符串分割成单词列表。然后,我们可以遍历words列表中的每个单词,并使用find()函数找到该单词在text中的位置。
以下是解决这个问题的代码示例:
- text = input("请输入text的内容:")
- words = input("请输入words的内容:")
- x = []
- # 将text字符串分割成单词列表
- text_words = text.split()
- # 遍历words列表中的每个单词
- for word in words.split():
- positions = []
- # 在text中查找该单词的位置
- for i, text_word in enumerate(text_words):
- if text_word == word:
- positions.append([i, i+len(word)-1])
- x.extend(positions)
- # 按照位置的起始位置进行排序
- x.sort()
- print(x)
复制代码
希望能帮助到你!如果还有其他问题,请随时提问。 |
|