python - 在 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()
解决方案
推荐阅读
- javascript - ChartJS 多注解(竖线)
- laravel - 从 Vue 组件取回数据
- gitlab - 完成后gitlab中的作业状态
- java - Spring JPA 规范-arg-resolver
- scala - IntelliJ 工作表期间的循环定义错误
- arrays - 合并 2 个具有相似键的 JSON 对象:ReactJS
- java - 如何使用 Java 转储 MySQL 数据库?
- javascript - 如何让我的表单在用户键入时指示模式不匹配错误(自定义验证错误)?
- javascript - AsyncFunction.apply 不是函数
- c - 用 union 的大小定义指向内存的指针