简体   繁体   English

如何从两个不同的txt文件中对数字进行排序然后将它们另存为一个txt文件

[英]How to sort numbers from two different txt files then save them as one txt file

Could anyone help please.任何人都可以请帮忙。 I have the following task:我有以下任务:

  • Create a new Python file in this folder called ​combined.py在此文件夹中创建一个名为 combined.py 的新 Python 文件
  • Create a text file called ​numbers1.txt that contains Integers which are sorted from smallest to largest.创建一个名为 numbers1.txt 的文本文件,其中包含从最小到最大排序的整数。

  • Create another text file called ​numbers2.txt which also contains Integers that are sorted from smallest to largest.创建另一个名为 numbers2.txt 的文本文件,其中还包含从最小到最大排序的整数。

  • Write the numbers from both files to a third file called ​all_numbers.txt将两个文件中的数字写入名为 all_numbers.txt 的第三个文件

  • All the numbers in ​all_numbers.txt should be sorted from smallest to largest. all_numbers.txt 中的所有数字应从小到大排序。

the 2 txt files are as follows: 2个txt文件如下:

numbers1:数字1:

20
10
30
50
40
60

then:然后:

numbers2:数字2:

999
80
150
101
100

The following code below takes the two txt files and saves them as one file correctly.下面的代码将两个txt文件正确保存为一个文件。 I'm just having some trouble sorting the integers from lowest to highest.我只是在将整数从最低到最高排序时遇到了一些麻烦。 Any help will be greatly appreciated!任何帮助将不胜感激! Thank you!谢谢!

filenames = ['numbers1.txt', 'numbers2.txt']
with open('all_numbers.txt', 'w') as outfile:
    for a in filenames:
        with open(a) as infile:
            outfile.write(infile.read() + "\n")
print("Your file is saved under all_numbers.txt")

It sounds like a simple merge would be best, we'll use sorted to keep things simple for now.听起来最好是简单的合并,我们现在将使用sorted来保持简单。

First, you should modularize your code a bit so that the logic of each section is clear.首先,您应该将代码模块化一点,以便每个部分的逻辑清晰。 Let's extract the numbers from each file into a list using a function:让我们使用函数将每个文件中的数字提取到列表中:

def load_numbers(filepath):
    with open(filepath, 'r') as file:
        return [int(n) for n in file.readlines()]

We can now invoke it to load our numbers into a list:我们现在可以调用它来将我们的数字加载到一个列表中:

first_numbers = load_numbers('numbers1.txt')
second_numbers = load_numbers('numbers2.txt')

Now we need a way to merge these two lists and ensure they're sorted.现在我们需要一种方法来合并这两个列表并确保它们已排序。 Using Python's sorted we can do:使用 Python 的sorted我们可以做到:

sorted_numbers = sorted(first_numbers + second_numbers)

Joe's answer has a great way to extend this to multiple lists using sum . Joe 的回答有一种很好的方法可以使用sum将其扩展到多个列表。

To write this to file we can do something similar to what we did with reading:要将其写入文件,我们可以执行类似于读取操作的操作:

with open('all_numbers.txt', 'w') as file:
    file.writelines(sorted_numbers)

Altogether:共:

def load_numbers(filepath):
    with open(filepath, 'r') as file:
        return [int(n) for n in file.readlines()]


if __name__ = '__main__':
    first_numbers = load_numbers('numbers1.txt')
    second_numbers = load_numbers('numbers2.txt')

    sorted_numbers = sorted(first_numbers + second_numbers)

    with open('all_numbers.txt', 'w') as file:
        file.writelines(sorted_numbers)

Currently you are writing the contents of each input file to the output as soon as you read them ( outfile.write(infile.read() + "\\n") ).当前,您在读取每个输入文件的内容后立即将其写入输出( outfile.write(infile.read() + "\\n") )。 To process them, I would suggest you read them first into lists, then work from there.要处理它们,我建议您先将它们读入列表,然后从那里开始工作。

To create a list of integers from each file, there are numerous methods.要从每个文件创建整数列表,有多种方法。 One is to read the entire file to a string with .read() , strip any excess whitespace and newlines with .strip() and split on newlines.一个是将整个文件中读取到用字符串.read()剥去任何过量的空白和与换行.strip()和换行分割。 You can then use a list comprehension or a map or some equivalent methodology to convert this list of strings of numbers to a list of integers.然后,您可以使用列表推导式或映射或某种等效方法将这个数字字符串列表转换为整数列表。

Then you need to combine these two lists and sort them.然后你需要将这两个列表组合起来并进行排序。 There are many algorithms for this.有很多算法可以做到这一点。 Seeing as your task has not specified, you could just use the built-in sorted() function or the list method .sort() .鉴于您的任务尚未指定,您可以使用内置的sorted()函数或列表方法.sort() This would have to operate on a list consisting of the two lists concatenated together.这必须对由连接在一起的两个列表组成的列表进行操作。 To concatenate two lists in Python, we can just add them ( [1, 2] + [3, 4] == [1, 2, 3, 4] ).要在 Python 中连接两个列表,我们可以将它们相加( [1, 2] + [3, 4] == [1, 2, 3, 4] )。

Therefore, your final solution could look something like:因此,您的最终解决方案可能类似于:

filenames = ['numbers1.txt', 'numbers2.txt']
num_lists = [[int(x) for x in open(f).read().strip().split('\n')] \
             for f in filenames]
with open('all_numbers.txt', 'w') as outfile:
    outfile.write('\n'.join(str(x) for x in sorted(sum(num_lists, []))) + '\n')

print('Your file is saved under all_numbers.txt')

Note that sum(numbers_list, []) is equivalent to numbers_list[0] + numbers_list[1] , but is better as your solution will now work for any number of input files.请注意, sum(numbers_list, [])等效于numbers_list[0] + numbers_list[1] ,但更好,因为您的解决方案现在适用于任意数量的输入文件。 :) :)

Test测试

$ echo '20
> 10
> 30
> 50
> 40
> 60' > numbers1.txt
$ echo '999
> 80
> 150
> 101
> 100' > numbers2.txt
$ python -q
>>> filenames = ['numbers1.txt', 'numbers2.txt']
>>> num_lists = [[int(x) for x in open(f).read().strip().split('\n')] \
...              for f in filenames]
>>> with open('all_numbers.txt', 'w') as outfile:
...     outfile.write('\n'.join(str(x) for x in sorted(sum(num_lists, []))) + '\n')
... 
37
>>> print('Your file is saved under all_numbers.txt')
Your file is saved under all_numbers.txt
>>> 
$ cat all_numbers.txt 
10
20
30
40
50
60
80
100
101
150
999

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从python的txt文件中提取两列数字并绘制它们 - Extracting two columns of numbers from a txt file in python and plot them 如何对相同的字符串求和并从 python 中的 txt 文件中对它们进行排序 - How to sum identical strings and sort them from txt file in python 如何从已拆分的.txt文件中获取多行并将其保存到不同的变量中 - How to get multiple lines from a .txt file that have been split and to save them into different variables 如何从 Spotipy 获取歌曲列表,然后将它们保存到 txt 文件? - How to get list of songs from Spotipy and then save them to a txt file? 如何从 a.txt 文件中读取值并将它们保存到 python 中的不同变量中并访问它们? - How can I read values from a .txt-file and save them into different variables in python and get access to them? 如何将两个值从.txt 分离到两个不同的文件? - How to separe two values from .txt to two different files? 如何从 .t​​xt 列表中获取数字并将结果保存在另一个 .txt 中? - How to take numbers from a .txt list and save the result in another .txt? 如何将txt文件中的两个字符串二进制数相乘 - How to multiply two string binary numbers from txt file Python 请求:从一个 TXT 文件中获取所有行,一次获取一个请求并将它们保存到一个新的 TXT 文件中 - Python Requests: take all lines from a TXT file, one at a time to get requests from each and save them to a new TXT file 出现在两个单独的txt文件中的行,从一个txt文件中删除 - Rows that appear in two separate txt files, remove from one txt file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM