【问题标题】:Merge Two wordlists into one file将两个单词表合并到一个文件中
【发布时间】:2016-06-14 17:50:31
【问题描述】:

我有两个单词表,如下例所示:

单词表 1:

code1
code2
code3

词表 2:

11
22
23

我想取 wordlist 2 并将每个数字与 wordlist 1 中的第一行放在一行中

输出示例:

code111
code122
code123
code211
code222
code223
code311
.
.

你能帮我看看怎么做吗?谢谢!

【问题讨论】:

  • 到目前为止,您尝试过哪些代码,效果如何?
  • 很遗憾:(我没试过我知道如何创建一个单词表但不合并两个:(
  • 你熟悉 for 循环和嵌套 for 循环吗?这可能会有所帮助。 wiki.python.org/moin/ForLoop
  • 我使用循环,但这是我第一次听到嵌套循环,谢谢你有时间我会检查链接
  • 上一个问题stackoverflow.com/questions/1821471/python-nested-loop 可能对复习有用。

标签: linux merge brute-force


【解决方案1】:

您可以运行两个嵌套的 for 循环来遍历这两个列表,并将连接的字符串附加到一个新列表中。
这是一个小例子:

## create lists using square brackets
wordlist1=['code1', ## wrap something in quotes to make it a string
           'code2','code3']
wordlist2=['11','22','23']

## create a new empty list
concatenated_words=[]

## first for loop: one iteration per item in wordlist1
for i in range(len(wordlist1)):
    ## word with index i of wordlist1 (square brackets for indexing)
    word1=wordlist1[i]
    ## second for loop: one iteration per item in wordlist2
    for j in range(len(wordlist2)):
        word2=wordlist2[j]
        ## append concatenated words to the initially empty list
        concatenated_words.append(word1+word2)

## iterate over the list of concatenated words, and print each item
for k in range(len(concatenated_words)):
    print(concatenated_words[k])

【讨论】:

  • 我尝试将列表更改为文件,但结果出错
  • 如果您安装了 python,请打开文本编辑器,粘贴代码示例,然后将其保存到名为 string_concatenation.py 的文件(python 文件)中。然后,打开终端,导航到文件所在的文件夹,然后输入python string_concatenation.py。这应该在您的终端中打印所需的输出。
  • 不,我的意思是 wordlist2 我想从 file.txt 中获取它
【解决方案2】:

list1 = ["text1","text2","text3","text4"] list2 = [11,22,33,44] 定义迭代连接(list1,list2): 结果 = [] 对于我在范围内(len(list2)): 对于范围内的 j(len(list1)): 结果 = 结果 + [str(list1[i])+str(list2[j])] 返回结果

【讨论】:

    【解决方案3】:

    你明白了吗?取决于您是否要在每个列表上输入名称,或者您是否希望它自动读取然后附加或扩展一个新的文本文件?我正在研究一个小脚本 atm 和一个非常快速和简单的方法,假设你希望所有文本文件都在你拥有 .py 文件的同一文件夹中:

    import os
    
    #this makes a list with all .txt files in the folder.
    list_names = [f for f in os.listdir(os.getcwd()) if f.endswith('.txt')]
    for file_name in list_names:
        with open(os.getcwd() + "/" + file_name) as fh:
            words = fh.read().splitlines()
    
    with open(outfile, 'a') as fh2:
        for word in words:
            fh2.write(word + '\n')
    

    【讨论】:

      猜你喜欢
      • 2013-09-15
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 2013-12-04
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多