Python 每三个字拆分一次文件&;创建三胞胎列表

Python 每三个字拆分一次文件&;创建三胞胎列表,python,arrays,python-3.x,list,split,Python,Arrays,Python 3.x,List,Split,我有一个txt文件,里面有一个用Python导入的文本,我想每3个单词将它分开 比如说, Python是一种解释性的高级通用编程语言 我想 [['Python','is','an'],['expressed','high-level','and'],['general-purpose','programming','language']. 我的代码到目前为止 lines = [word.split() for word in open(r"c:\\python\4_TRIPLETS\S

我有一个txt文件,里面有一个用Python导入的文本,我想每3个单词将它分开

比如说,

Python是一种解释性的高级通用编程语言

我想

[['Python','is','an'],['expressed','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.']]

有什么想法吗?

使用列表理解将列表转换为
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)

使用列表理解将列表转换为
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)

您可以使用拆分字符串分隔每个单词,然后浏览列表并将它们分组为3个单词对

   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)            

您可以使用拆分字符串分隔每个单词,然后浏览列表并将它们分组为3个单词对

   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)            

使用正则表达式尝试不使用onelinerTry。这能回答你的问题吗?使用正则表达式尝试不使用onelinerTry。这能回答你的问题吗?