簡體   English   中英

如何迭代 Python 中的詞匯表?

[英]How do I iterate over a vocabulary list in Python?

這就是我的意思:假設我有一個清單。 我們稱之為消息。

messages = ['hey how are you', 'doing good what about you']

我的最終目標是針對另一個詞匯表運行此列表,如果每個單詞都在詞匯表中,則將其放入另一個中。 這個詞匯表看起來是這樣的:

vocab = ['hey', 'how', 'you']

(注意'are'被省略)
我的格式化數據的最終列表現在看起來像這樣:

final_list = np.array([['', '', '', ''], ['', '', '', '']])

我希望它看起來像這樣:

final_list = np.array([['hey', 'how', 'you', ''], ['you', '', '', '']])

我有一個使用for循環和enumerate()的想法,但效果不佳。 幫助將不勝感激!

查看消息列表。 對於每條消息,將其拆分為單詞,最多取 N (N=4) 個單詞,並根據需要填充空字符串。

N = 4
data = []
for m in messages:
    words = [x for x in m.split() if x in vocab]
    data.append(words[:N] + (N - len(words)) * [""])
final_list = np.array(data)

為了獲得更好的性能,在循環之前將vocab轉換為一個集合:

vocab = set(vocab)

結果:

array([['hey', 'how', 'you', ''],
       ['you', '', '', '']], dtype='<U3')

嘗試使用兩個 for 循環:

vocab = ['hey', 'how', 'you']
messages = ['hey how are you', 'doing good what about you']
m = []
s = []
for x in messages:
  for y in x.split():
    if y in vocab:
      s.append(y)
  m.append(s)
  s = []
    
print(m)

獲取空元素:

vocab = ['hey', 'how', 'you']
messages = ['hey how are you', 'doing good what about you']
m = []
s = []
for x in messages:
  for y in x.split():
    if y in vocab:
      s.append(y)
    else:
      s.append('')
  m.append(s)
  s = []
    
print(m)

列表理解是一種有效的方法。 然后,如果需要,您可以將輸出轉換為數組。

li = ['hey how are you', 'doing good what about you']
vocab = ['hey', 'how', 'you']

final_list = [[el if el in el2 else '' for el in vocab] for el2 in li]

print(final_list)

輸出:

[['hey', 'how', 'you'], ['', '', 'you']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM