如何在python中使用每行的字数拆分文本文件,而不使用模块
因此,我正在编写这个脚本,其中一个文本文件将根据每行的单词量拆分为列表,我需要生成一个字典,但不需要担心它;我在尝试拆分此文本时遇到问题: 让我们假设我有:如何在python中使用每行的字数拆分文本文件,而不使用模块,python,python-3.x,Python,Python 3.x,因此,我正在编写这个脚本,其中一个文本文件将根据每行的单词量拆分为列表,我需要生成一个字典,但不需要担心它;我在尝试拆分此文本时遇到问题: 让我们假设我有: word1: word word more words word2: another word word3: word4: 我想: [[[word:], [word word], [more words]],[[word2:], [another word]], [[word3:]], [[word4:]]] 代码如下: from
word1:
word word
more words
word2:
another word
word3:
word4:
我想:
[[[word:], [word word], [more words]],[[word2:], [another word]],
[[word3:]], [[word4:]]]
代码如下:
from typing import List, Dict, TextIO, Tuple
def read_file(TextIO) -> Dict[str, List[tuple]]:
text = open('text_file.txt', 'r')
data = []
indexes = []
for line in text.readlines():
l = line.strip().split(',')
data.append(l)
for lists in data:
if lists == ['']:
data.remove(lists)
for elements in data:
if len(elements) == 1:
if ':' in elements[0][-1]:
indexes.append(data.index(elements))
我如何使用索引在我需要的部分中剪切数据?或者,我如何在不使用模块的情况下将文本文件剪切到所需的部分?您正在执行一系列毫无意义的操作–可能是以前尝试的遗留操作。您没有任何包含逗号的数据,因此
.split(',')
已过时。我也看不到附加到索引
应该做什么
相反,采取以下方法:将以:
结尾的单词作为新列表追加;将所有其他短语附加到最后一个列表中。唯一与此不同的是空白行;这似乎应该被丢弃,否则它将在其中一个列表中添加一个'
因此,所需的只是这个简短的代码:
data = []
with open('text.txt', 'r') as text:
for line in text:
line = line.strip()
if line:
if line.endswith(':'):
data.append([line])
else:
data[-1].append(line)
print (data)
按要求输出:
[['word1:', 'word word', 'more words'], ['word2:', 'another word'], ['word3:'], ['word4:']]
循环中没有理由出现
text.readlines()
。只需对文本中的行执行:
,因为文件是可编辑的。