Удалить эти строки из текстового файла, если строка содержит только одно из стоп-слов - PullRequest
0 голосов
/ 06 марта 2019

Я хочу удалить только эти строки из файла Myfile.txt, если строка содержит только один текст и содержит только одно из стоп-слов

Например, образец файла Myfile.txt равен

Adh Dhayd
Abu Dhabi is      # here is "is" stopword but this line should not be removed because line contain #Abu Dhabi is
Zaranj
of                # this line contains just stop word, this line should be removed
on                # this line contains just stop word, this line should be removed
Taloqan
Shnan of          # here is "of" stopword but this line should not be removed because line contain #Shnan of
is                # this line contains just stop word, this line should be removed
Shibirghn
Shahrak
from              # this line contains just stop word, this line should be removed

У меня есть этот код в качестве примера

import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize



example_sent = "This is a sample sentence, showing off the stop words filtration."

stop_words = set(stopwords.words('english'))

word_tokens = word_tokenize(example_sent)

filtered_sentence = [w for w in word_tokens if not w in stop_words]

filtered_sentence = []

for w in word_tokens:
    if w not in stop_words:
        filtered_sentence.append(w)

print(word_tokens)
print(filtered_sentence)

Так, каков будет код решения для Myfile.txt согласно упомянутому выше.

1 Ответ

0 голосов
/ 06 марта 2019

Вы можете посмотреть, соответствует ли строка какому-либо из стоп-слов, если не добавить его к отфильтрованному контенту. Это если вы хотите отфильтровать все строки, которые содержат только один stop_word. Если также необходимо отфильтровать строку с несколькими стоп-словами, попробуйте разбить ее на строки и построить пересечение с помощью stop_words:

f = open("test.txt","r+")
filtered_content = []
stop_words = set(stopwords.words('english'))
for line in f.read().splitlines():
    if not line in stop_words:
        filtered_content.append(line)
g = open("test_filter.txt","a+")
g.write("\n".join(filtered_content))
g.close()
f.close()

Если вы хотите удалить несколько стоп-слов, используйте это выражение if. Это удаляет строку, которая содержит только стоп-слова. Если одно слово не является стоп-словом, строка сохраняется:

if not len(set(word_tokenize(line)).intersection(stop_words)) == len(word_tokenize(line)):
...