📅  最后修改于: 2023-12-03 15:19:11.449000             🧑  作者: Mango
Python编程语言提供了多种方法来获取两个单词之间的单词。下面是一些可行的方法:
可以使用Python内置的re模块中的findall()函数和正则表达式来获取两个单词之间的单词。
import re
def get_words_between(text, word1, word2):
pattern = r"{}(\s+\w+\s+){}".format(word1, word2)
result = re.findall(pattern, text)
if result:
return result[0].split()
else:
return None
该函数使用正则表达式构建一个匹配模式以找到两个单词之间所有的单词,并返回它们的列表。
text = "Python is an interpreted, high-level, general-purpose programming language."
words = get_words_between(text, "interpreted,", "general-purpose")
print(words) # ['high-level,']
另一种方法是使用列表解析,将输入字符串分割成单词列表,并从中提取出两个单词之间的单词。
def get_words_between(text, word1, word2):
words = text.split()
start_index = words.index(word1) + 1
end_index = words.index(word2)
if start_index >= end_index:
return None
return words[start_index:end_index]
该函数将输入字符串拆分为单个单词,并找到了两个单词的索引。然后使用列表解析从列表中提取这些单词。
text = "Python is an interpreted, high-level, general-purpose programming language."
words = get_words_between(text, "interpreted,", "general-purpose")
print(words) # ['high-level,']
可以使用split()函数来拆分字符串,然后使用join()函数将两个单词之间的单词组成一个新的字符串。
def get_words_between(text, word1, word2):
words = text.split()
start_index = words.index(word1) + 1
end_index = words.index(word2)
if start_index >= end_index:
return None
return " ".join(words[start_index:end_index])
text = "Python is an interpreted, high-level, general-purpose programming language."
words = get_words_between(text, "interpreted,", "general-purpose")
print(words) # 'high-level,'
以上三种方法都可以用于获取任意两个单词之间的单词。根据你的具体需求选择最适合你的方法即可。