如何将两个txt文件正确组合到一个列表中

时间:2018-02-23 02:48:17

标签: python-3.x

这样做的目的是从用户那里获取两个文本输入组合它们然后打印元素。我想我沿着正确的道路前进,但是当我运行这段代码时,我得到了一个巨大的表格,其中的元素完全没有意义。 这是我目前的代码:

      defining the read function
def read(pulsar_name,signal_strength):
    #opening and reading data from first line
    pulsars = open(pulsar_name,"r").read()
    #opening and reading data from second line
    signals = open(signal_strength,"r").read()
    #creating a new empty list
    astro_list = []
    #appending pulsar values to list
    for all_pulsar_name in range(0,len(pulsars)):
        astro_list.append(pulsar_name)
    #appending signal data to list
    for all_signal_strength in range(0,len(signals)):
        astro_list.append(signal_strength)
    with open("z.txt", "w") as out:
        for i in range(0,len(astro_list)):
            return(pulsar_name[i].rstrip(),signal_strength[i])

#defining the main function
def main():

    #displaying a description of what the program does
    purpose = "This program proccess data from the Purdue Pulsar Laboratory"
    underheading = "=" * len(purpose)
    print(purpose)
    print(underheading)
    print("It reads the data from 2 files containing the pulsar name and signal strength, \nthen combines them and displays the results.")
    #accepting inputs from the user about file names
    pulsar_name = input("\nPulsar name file: ")
    signal_strength = input("Signal strength: ")
    #calling
    astro_list = read(pulsar_name,signal_strength)
    read(pulsar_name,signal_strength)
    #reading values
    print("\nAnalyzing data from" , pulsar_name, "and", signal_strength, "files...")
    print("     ","Reading from" ,pulsar_name,"...")
    print("     ","Reading from" ,signal_strength,"...")
    print("     ","Combining values...")
    #displaying the top part of the table/ counting the number of elements that are in the list
    print("\nThe combined BOOYA data includes" ,len(astro_list), "values.")
    print(astro_list)


if __name__ == '__main__':
    main()

我知道你们都无法访问这些文件,而且可能会把它们交给你们很痛苦,但我只需要知道如何基本结合我已经拥有的列表。 read函数应该采用我已经确定的两个参数。我并没有完全得到错误代码,只是因为我知道我没有正确地组合这些列表。输出的一个示例是,一个文本文件将具有ALPHABET,一个将具有NUMBERS例如:

enter image description here

这就是我的代码输出现在的样子。 enter image description here

1 个答案:

答案 0 :(得分:0)

作为评论中提到的@francium,我假设脉冲星数据和信号数据具有相同的长度并修改了读取功能。

def read(pulsar_name,signal_strength):
    astro_list = []
    #open the files
    with open(pulsar_name, 'r') as p, open(signal_strength, 'r') as s:
        #read both of the files
        pulsar_lines = p.readlines()
        signal_lines = s.readlines()

        for i in range(len(pulsar_lines)):
            #strip each line and split it on spaces on both files
            pline = pulsar_lines[i].strip().split()
            sline = signal_lines[i].strip().split()
            astro_list.append([])

            #take element from pline and sline and combine them
            for j in range(len(pline)):
                astro_list[-1].append(pline[j].capitalize() + sline[j])

    #write the astro_list to file named z.txt
    with open('z.txt', 'w') as out:
        for i in range(len(astro_list)):
            out.write(' '.join(astro_list[i]))
            out.write('\n')

    return astro_list

#defining the main function
def main():

    #displaying a description of what the program does
    purpose = "This program proccess data from the Purdue Pulsar Laboratory"
    underheading = "=" * len(purpose)
    print(purpose)
    print(underheading)
    print("It reads the data from 2 files containing the pulsar name and signal strength, \nthen combines them and displays the results.")
    #accepting inputs from the user about file names
    pulsar_name = input("\nPulsar name file: ")
    signal_strength = input("Signal strength: ")
    #calling
    astro_list = read(pulsar_name,signal_strength)
    #reading values
    print("\nAnalyzing data from" , pulsar_name, "and", signal_strength, "files...")
    print("     ","Reading from" ,pulsar_name,"...")
    print("     ","Reading from" ,signal_strength,"...")
    print("     ","Combining values...")
    #displaying the top part of the table/ counting the number of elements that are in the list
    print("\nThe combined BOOYA data includes" ,len(sum(astro_list, [])), "values.")
    print(underheading)
    for l in astro_list:
        print(*l)

if __name__ == '__main__':
    main()

以下是我的 signal.txt

1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1

pulsar.txt

A B C D E F G H
I J K L M N O P

运行上述程序时的输出:

This program proccess data from the Purdue Pulsar Laboratory
============================================================
It reads the data from 2 files containing the pulsar name and signal strength,
then combines them and displays the results.

Pulsar name file: pulsar.txt
Signal strength: signal.txt

Analyzing data from pulsar.txt and signal.txt files...
      Reading from pulsar.txt ...
      Reading from signal.txt ...
      Combining values...

The combined BOOYA data includes 16 values.
============================================================
1A 2B 3C 4D 5E 6F 7G 8H
8I 7J 6K 5L 4M 3N 2O 1P