从列表中提取关键字的Python程序
给定 List of 字符串,提取所有作为关键字的单词。
Input : test_list = [“Gfg is True”, “Its a global win”, “try Gfg”],
Output : [‘is’, ‘True’, ‘global’, ‘try’]
Explanation : All strings in result list is valid Python keyword.
Input : test_list = [“try Gfg”],
Output : [‘try’]
Explanation : try is used in try/except block, hence a keyword.
方法 #1:使用 iskeyword() + split() + 循环
这是可以执行此任务的方法之一。在这里,我们使用 iskeyword() 检查关键字并使用 split() 将字符串转换为单词。扩展到所有字符串的逻辑使用循环发生。
Python3
# Python3 code to demonstrate working of
# Extract Keywords from String List
# Using iskeyword() + loop + split()
import keyword
# initializing list
test_list = ["Gfg is True", "Gfg will yield a return",
"Its a global win", "try Gfg"]
# printing original list
print("The original list is : " + str(test_list))
# iterating using loop
res = []
for sub in test_list:
for word in sub.split():
# check for keyword using iskeyword()
if keyword.iskeyword(word):
res.append(word)
# printing result
print("Extracted Keywords : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Keywords from String List
# Using list comprehension
import keyword
# initializing list
test_list = ["Gfg is True", "Gfg will yield a return",
"Its a global win", "try Gfg"]
# printing original list
print("The original list is : " + str(test_list))
# One-liner using list comprehension
res = [ele for sub in test_list for ele in sub.split() if keyword.iskeyword(ele)]
# printing result
print("Extracted Keywords : " + str(res))
输出:
The original list is : [‘Gfg is True’, ‘Gfg will yield a return’, ‘Its a global win’, ‘try Gfg’]
Extracted Keywords : [‘is’, ‘True’, ‘yield’, ‘return’, ‘global’, ‘try’]
方法#2:使用列表理解
这是可以执行此任务的另一种方式。与上述方法类似,但在纸面上更紧凑,使用与上述方法类似的功能。
蟒蛇3
# Python3 code to demonstrate working of
# Extract Keywords from String List
# Using list comprehension
import keyword
# initializing list
test_list = ["Gfg is True", "Gfg will yield a return",
"Its a global win", "try Gfg"]
# printing original list
print("The original list is : " + str(test_list))
# One-liner using list comprehension
res = [ele for sub in test_list for ele in sub.split() if keyword.iskeyword(ele)]
# printing result
print("Extracted Keywords : " + str(res))
输出:
The original list is : [‘Gfg is True’, ‘Gfg will yield a return’, ‘Its a global win’, ‘try Gfg’]
Extracted Keywords : [‘is’, ‘True’, ‘yield’, ‘return’, ‘global’, ‘try’]