Python/NLTK停止字和文件Wri出现问题

2024-03-29 11:03:11 发布

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

我正试图写一份NLTK的停止词列表。你知道吗

所以,我写了这个剧本:

import nltk
from nltk.corpus import stopwords
from string import punctuation

file_name = 'OUTPUT.CSV'
file = open(file_name, 'w+')  
_stopwords = set(stopwords.words('english')+list(punctuation)) 
i = 0
file.write(f'\n\nSTOP WORDS:+++\n\n')
for w in _stopwords:
    i=i+1
    out1 = f'{i:3}. {w}\n'
    out2 = f'{w}\n'
    out3 = f'{i:3}. {w}'
    file.write(out2)
    print(out3)

file.close()

最初的程序使用file.write(w),但是自从我遇到问题,我就开始尝试一些东西。你知道吗

所以,我试着用file.write(out1)。这是可行的,但停止词的顺序似乎是随机的。你知道吗

有趣的是,如果我使用file.write(out2),我只写一个随机数的停止词,看起来是以随机顺序出现的,总是少211个。我在Visual Studio 2017和Jupyter笔记本中都遇到了相同的问题。你知道吗

例如,最后一次跑步写了175个单词,结尾是:

its
wouldn
shan 

使用file.write(out1)我得到所有211个单词,列结尾如下:

209. more
210. have
211. ,

有没有人遇到过类似的问题。你知道会发生什么吗?你知道吗

我是Python/NLTK的新手,所以我决定问一下。你知道吗


Tags: namefromimport顺序结尾单词filewrite
1条回答
网友
1楼 · 发布于 2024-03-29 11:03:11

你得到一个随机顺序的停止词的原因是由于使用了set。你知道吗

_stopwords = set(stopwords.words('english')+list(punctuation)) 

集合是没有重复元素的无序集合。阅读更多here。你知道吗

Unlike arrays, where the elements are stored as ordered list, the order of elements in a set is undefined (moreover, the set elements are usually not stored in order of appearance in the set; this allows checking if an element belongs to a set faster than just going through all the elements of the set).

您可以使用这个简单的示例来检查:

test = set('abcd')
for i in test: 
    print(i) 

它输出不同的顺序(例如,我尝试了两个不同的系统,这是我得到的): 论Ist制度

a
d
b
c

而且, 关于第二个系统

d
c
a
b

对于有序集还有其他的选择。检查here。你知道吗


此外,我检查了所有三个out1out2out3都给出了211个停止词。你知道吗

相关问题 更多 >