【问题标题】:Python word to id representationPython word to id 表示
【发布时间】:2017-11-20 15:06:06
【问题描述】:

我试图用数字表示一组单词。到目前为止我有这个代码:

from sklearn.preprocessing import OneHotEncoder
import itertools
docs = ["select", "max", "income", "from", "data", "where", "revenue", "between", "20", "40"]

# split documents to tokens
tokens_docs = [doc.split(" ") for doc in docs]

# convert list of of token-lists to one flat list of tokens
# and then create a dictionary that maps word to id of word,
# like {A: 1, B: 2} here
all_tokens = itertools.chain.from_iterable(tokens_docs)
word_to_id = {token: idx for idx, token in enumerate(set(all_tokens))}

但是,有一个限制 - 当令牌本身已经是一个数字时,我需要分配与数字相同的值(在 word_to_id 字典中)。 有什么建议吗?

【问题讨论】:

    标签: python nlp one-hot-encoding


    【解决方案1】:

    您可以在 dict 理解中再添加一个条件,并使其更短,请使用 if 表达式的简写:what_if_True if if_statement what_if_else。像这样:

    word_to_id = {token: token if token.isdigit() else idx for idx, token in enumerate(set(all_tokens))}
    

    【讨论】:

    • 虽然这可能会回答这个问题,但一些 cmets 和/或解释会很好。这也将帮助其他用户。
    【解决方案2】:

    您可以在字典理解中使用if else 语句。

    {token: idx if not token.isdigit() else int(token)
                 for idx, token in enumerate(set(all_tokens)}
    

    这将返回{'4': 4, '5': 5, 'df': 1, 'dfg': 4, 'fd': 0, 'fg': 3}
    如果输入是['fd', 'df', '5', 'fg', 'dfg', '4']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2022-12-01
      • 2022-12-01
      • 2013-09-02
      • 2023-03-21
      • 2017-06-26
      • 1970-01-01
      相关资源
      最近更新 更多