📜  Python – 单词的序列分配

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

Python – 单词的序列分配

给定一个单词字符串,为每个单词分配索引。

方法 #1:使用 enumerate() + dict() + split()

在此,我们首先执行 split() 的任务,然后使用 enumerate() 添加索引组件以将每个单词映射到索引。

Python3
# Python3 code to demonstrate working of 
# Sequence Assignment to Words
# Using split() + enumerate() + dict()
  
# initializing string
test_str = 'geekforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# using dict() to convert result in idx:word manner 
res = dict(enumerate(test_str.split()))
      
# printing result 
print("The Assigned Sequence : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Sequence Assignment to Words
# Using zip() + count() + dict()
from itertools import count
  
# initializing string
test_str = 'geekforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# using dict() to convert result in idx:word manner 
# count() from itertools used for this task
res = dict(zip(count(), test_str.split()))
      
# printing result 
print("The Assigned Sequence : " + str(res))


输出
The original string is : geekforgeeks is best for geeks
The Assigned Sequence : {0: 'geekforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'}

方法#2:使用 zip() + count() + dict()

在此,count() 组件呈现索引逻辑,每个单词与索引的配对是使用 zip() 完成的。

Python3

# Python3 code to demonstrate working of 
# Sequence Assignment to Words
# Using zip() + count() + dict()
from itertools import count
  
# initializing string
test_str = 'geekforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# using dict() to convert result in idx:word manner 
# count() from itertools used for this task
res = dict(zip(count(), test_str.split()))
      
# printing result 
print("The Assigned Sequence : " + str(res)) 
输出
The original string is : geekforgeeks is best for geeks
The Assigned Sequence : {0: 'geekforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'}