首页 > 解决方案 > 在 Python 3 中将文件内容写入文件时显示空白列表 [] [] [] []?

问题描述

我想(阅读)这本书(在文本文件中),因为它是当前形式。书的格式是文本文件,比如

在美国数学学会会刊中,第 9 卷,第 541-544 页,1958 年。 [314] R. De Nicola 和 F. Vaandrager。分支双模拟的三种逻辑(扩展摘要)。在第五届年度 IEEE 计算机科学逻辑研讨会 (LICS),第 118-129 页。IEEE 计算机协会出版社,Springer-Verlag,1990。[315] X. Nicollin 和 J.-L。Richier 和 J. Sifakis 和 J. Voiron。ATP:定时过程的代数。在 IFIP TC2 编程概念和方法工作会议上,第 402-427 页。北荷兰,1990。

这本书可以是任何有 400 页或更多页的书(.txt 文件)。

我想要做的是,首先我将书中的每个句子(txt 文件)拆分为一个列表,使用sent_tokenize. 此后,现在该文件具有相对于输入文本文件的句子列表列表,我需要将文件(与句子列表列表一样)写入一个新文件。

程序执行成功,但是当我打开新生成的文件时,它应该包含列表语句,它打印空白 [][][]。我希望有一些编码问题。这是看起来像的输出

在此处输入图像描述 我有兴趣弄清楚这个问题。任何帮助表示赞赏。

我尝试过的代码如下:

import nltk, re
import string
from collections import Counter
from string import punctuation
from nltk.tokenize import TweetTokenizer, sent_tokenize, word_tokenize
from nltk.corpus import gutenberg, stopwords
from nltk.stem import WordNetLemmatizer

def remove_punctuation(from_text):
    table = str.maketrans('', '', string.punctuation)
    stripped = [w.translate(table) for w in from_text]
    return stripped

def preprocessing():
    with open("F:\\Pen Drive 8 GB\\PDF\\Code\\Books Handbooks\\Books Handbooks Text\\b1.txt", encoding="utf-8") as f:
         tokens_sentences = sent_tokenize(f.read())
         tokens = [[word.lower() for word in line.split()] for line in tokens_sentences]
         global stripped_tokens
         stripped_tokens = [remove_punctuation(i) for i in tokens]
         sw = (stopwords.words('english'))
         filter_set = [[token for token in sentence if (token.lower() not in sw and token.isalnum() and token.isalpha() and re.findall(r"[^_ .'\"-[A-Za-z]]+", token))] for sentence in stripped_tokens]
    lemma = WordNetLemmatizer()
    lem = []
    for w in filter_set:
        lem.append([wi for wi in map(lemma.lemmatize, w)])
    return lem
result = preprocessing()
with open('F:\\Pen Drive 8 GB\\PDF\\Code\\Books Handbooks\\Books Handbooks Text\\b1list.txt', "w", encoding="utf-8") as f:
    for e in result[:]:  
        f.write(str(e))
preprocessing() 

标签: pythonpython-3.xlistfilenltk

解决方案


推荐阅读