将字符串转换为标记列表的位置

2024-05-16 22:04:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大约5000个单词/标记的列表,每个单词(一个笑脸计为一个单词)是每行的。尝试为Im生成一些支持向量机的东西。在

假设示例列表只有几个单词

happy
sad
is
:(
i
the
day
am
today
:)

我的琴弦是:

^{pr2}$

则每条tweet的输出为:

5:1 8:1 1:1 9:1 10:1
3:1 9:1 6:1 2:1 4:1

注意这种格式:,这意味着冒号前的第一个数字应该使用单词在列表中的行号/位置来引用它。e、 g.“:)”是列表中的第十个单词(文本文件,每行1个标记)。在

我正在考虑创建一个函数来读取一个文本文件,并将每一行(每个单词/标记)放到列表或字典中的一个位置,这样我就可以从每条tweet中读取一个单词,并根据它在列表中的位置将其翻译成数字。在

有人知道如何在python中实现这一点吗? 然后我就这样想:

 for i in tweets:
         <translate-words-into-list-position>

Tags: the标记示例列表is数字单词向量
2条回答
words = ['happy', 'sad', 'is', ':(', 'i', 'the', 'day', 'am', 'today', ':)']
d = {w: i for i, w in enumerate(words, start=1)}
tweets =['i am happy today :)','is today the sad day :(']
for tweet in tweets:
    print ' '.join(['{0}:1'.format(d[w]) for w in tweet.split() if w in d])


5:1 8:1 1:1 9:1 10:1
3:1 9:1 6:1 2:1 7:1 4:1

如果words是file你仍然可以在这个解决方案中使用它,只需记住.rstrip('\n')行。例如

^{pr2}$
>>> from itertools import count
>>> D = dict(zip(words, count(1)))
>>> tweets =['i am happy today :)','is today the sad day :(']
>>> [["{}:1".format(D[k]) for k in t.split() if k in D] for t in tweets]
[['5:1', '8:1', '1:1', '9:1', '10:1'], ['3:1', '9:1', '6:1', '2:1', '7:1', '4:1']]

相关问题 更多 >