📜  Python – 字符串中的短语提取

📅  最后修改于: 2022-05-13 01:55:15.722000             🧑  作者: Mango

Python – 字符串中的短语提取

有时,在使用Python字符串时,我们可能会遇到一个问题,即我们需要提取字符串中的某些单词,不包括开头和后面的 K 个单词。这可以在许多领域中应用,包括所有那些包含数据的领域。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + enumerate() + 列表切片
上述方法的组合可以用来解决这个问题。在此,我们提取空间索引并根据空间索引执行切片。

# Python3 code to demonstrate working of 
# Phrase extraction in String
# Using list comprehension + enumerate() + list slicing
  
# initializing string
test_str = 'Geeksforgeeks is best for geeks and CS'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 2
  
# Phrase extraction in String
# Using list comprehension + enumerate() + list slicing
temp = [idx for idx, ele in enumerate(test_str) if ele == ' ']
res = test_str[temp[K - 1]: temp[-(K - 1)]].strip()
  
# printing result 
print("String after phrase removal : " + str(res)) 
输出 :
The original string is : Geeksforgeeks is best for geeks and CS
String after phrase removal : best for geeks and

方法 #2:使用join() + split()
上述方法的组合可用于执行此任务。在这里,我们拆分所有单词并加入除了初始和后 K 之外的所有单词。

# Python3 code to demonstrate working of 
# Phrase extraction in String
# Using join() + split()
  
# initializing string
test_str = 'Geeksforgeeks is best for geeks and CS'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 2
  
# Phrase extraction in String
# Using join() + split()
res = ' '.join(test_str.split()[K:-(K - 1)])
  
# printing result 
print("String after phrase removal : " + str(res)) 
输出 :
The original string is : Geeksforgeeks is best for geeks and CS
String after phrase removal : best for geeks and