【问题标题】:Concatenate two files in a loop to create new file?循环连接两个文件以创建新文件?
【发布时间】:2023-03-05 22:53:01
【问题描述】:

我正在尝试合并两个列表。它们都在名为 list1.txt 和 list2.txt 的文件中。我正在尝试将 list2.txt 中的单词附加到 list1.txt。例如:

list1.txt 有数千个类似的单词

  • 苹果
  • 兄弟
  • 朋友

list2.txt 有十几个类似的词

  • 地壳
  • 下雨

我想得到一个输出,它从 list2.txt 中获取所有单词并将它们连接到 list1.txt 中的每个单词。所以输出看起来像这样:

  • 苹果皮
  • 苹果湖
  • 苹果雨
  • 老兄
  • 兄弟湖

等等。我不确定如何完成这项工作。任何帮助表示赞赏。

【问题讨论】:

    标签: python bash


    【解决方案1】:

    使用join 得到笛卡尔积,使用tr 去掉分隔空间:

    $ join -o 1.1,2.1 -j 666 file1 file2 | tr -d ' '
    

    一些输出:

    applecrust
    applelake
    applerain
    ...
    

    解决方案是滥用文件中没有字段 666 的事实,并加入不存在的字段会产生文件中项目的笛卡尔积。

    【讨论】:

    • 谢谢,@詹姆斯布朗。这有帮助。
    【解决方案2】:

    我想这对你有帮助

    List = []
    list1 = open('list1.txt','r')
    total = ''
    for i in list1:
        List.append(i.strip())
    list1.close()
    for append_text in List:
        
        list2 = open('list2.txt','r')    
        for i in list2:
            final = str(append_text)+str(i)
            total = total+final
        total = total+'''\n'''
        list2.close()
    print(total)
    

    【讨论】:

    • 谢谢你。这可以解决问题。只是出于好奇,如果我想添加第三个列表会是什么样子?
    • 好的,我可以帮助你,但你能解释一下你想要第三个列表的内容吗?如果对你有帮助,请标记我的答案
    【解决方案3】:

    我不能保证这会给您具体的订单,但是:

    from itertools import product
    
    with open("output.txt", 'w') as output:
        with open('file1.txt', 'r' ) as file1, open('file2.txt','r') as file2:
           for word1, word2 in product(file1, file2):
               output.write(word1.strip() + word2.strip() + "\n")
    

    itertools.product() 将为您提供第一个文件中的单词和第二个文件中的单词的所有组合。

    【讨论】:

      【解决方案4】:

      你可以使用zip():

      with open("output.txt", 'a') as output:
          with open('file1.txt') as file1, open('file2.txt') as file2:
              for word1, word2 in zip(file1, file2):
                  output.write(word1 + word2 + "\n")
      

      它的作用是打开,一起解析它们并将其写入输出文件。

      编辑:这个问题已被投票,所以我认为这对你有用,但再次查看你的问题,我发现你需要不同的输出。这是修改后的代码:

      output = open("output.txt", 'a')
      file1 = open('file1.txt')
      file2 = open('file2.txt')
      for word in file1:
          for second_word in file2:
              output.write(word + second_word + "\n")
          file2.seek(0)
      output.close()
      file1.close()
      file2.close()
      

      对于 file1 中的每个单词,它会遍历 file2 中的所有单词并将它们相加。然后它移动到 file1 中的下一个单词,依此类推。

      【讨论】:

      • 我认为这不会满足您的需求 - 您会得到:applecrust Brotherlake friendlane 你不会得到任何其他的。
      • 啊,我明白了。没看到。
      • 编辑了我的答案。
      • 您的第二个代码 sn-p 将在第二个 for 循环第一次退出后立即耗尽第二个文件。
      • 唯一明智的做法是使用itertools.product() - 或者将每个文件中的所有内容读入一个列表并执行两个循环。
      猜你喜欢
      • 2021-06-28
      • 2019-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      • 2014-08-29
      • 1970-01-01
      相关资源
      最近更新 更多