我有一个txt文件,其中包含我用Python导入的文本,我希望每隔3个单词将它分开。
例如,
Python is an interpreted, high-level and general-purpose programming language
我想成为,
[['Python', 'is', 'an'],['interpreted,', 'high-level','and'],['general-purpose','programming','language']].
到目前为止我的代码,
lines = [word.split() for word in open(r"c:\\python\4_TRIPLETS\Sample.txt", "r")]
print(lines)给我这个输出,
[['Python', 'is', 'an', 'interpreted,', 'high-level', 'and', 'general-purpose', 'programming', 'language.', "Python's", 'design', 'philosophy', 'emphasizes', 'code', 'readability', 'with', 'its', 'notable', 'use', 'of', 'significant', 'whitespace.', 'Its', 'language', 'constructs', 'and', 'object-oriented', 'approach', 'aim', 'to', 'help', 'programmers', 'write', 'clear,', 'logical', 'code', 'for', 'small', 'and', 'large-scale', 'projects.']]有什么想法吗?
发布于 2021-01-10 16:52:34
使用列表理解将列表转换为n项的块
with open('c:\\python\4_TRIPLETS\Sample.txt', 'r') as file:
data = file.read().replace('\n', '').split()
lines = [data[i:i + 3] for i in range(0, len(data), 3)]
print(lines)发布于 2021-01-10 17:01:04
您可以使用一个拆分字符串来分隔每个单词,然后遍历列表并将它们分组成对三个单词。
final = = [None] * math.ceil(lines/3)
temp = [None] * 3
i = 0
for x in lines:
if(i % 3 == 0)
final.append(temp)
temp = [None] * 3
temp.append(x) https://stackoverflow.com/questions/65655808
复制相似问题