【问题标题】:Split file every three words & create lists of triplets每三个单词拆分文件并创建三元组列表
【发布时间】:2021-01-10 16:48:02
【问题描述】:

我有一个 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.']]

有什么想法吗?

【问题讨论】:

标签: python arrays python-3.x list split


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用拆分字符串来分隔每个单词,然后遍历列表并将它们分组为 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)            
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-07
      • 2022-01-05
      • 2020-09-21
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      相关资源
      最近更新 更多