Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中从文件中分别读取字符串和整数_Python_String_Integer - Fatal编程技术网

如何在python中从文件中分别读取字符串和整数

如何在python中从文件中分别读取字符串和整数,python,string,integer,Python,String,Integer,我读文件有困难。我有一个小的文本文件,就像下面的一样。我的程序应该读取第一个字符串,存储其余的整数,并按递增顺序排序。我必须用python编写我的程序,但我还没有弄明白。如何分离字符串和整数。最后,我用名称输出结果,并以整数排序 !/usr/bin/env/python 您可以使用regex和heapq: import re import heapq f = [i.strip('\n') for i in open('filename.txt')] new_f = [re.findall("(

我读文件有困难。我有一个小的文本文件,就像下面的一样。我的程序应该读取第一个字符串,存储其余的整数,并按递增顺序排序。我必须用python编写我的程序,但我还没有弄明白。如何分离字符串和整数。最后,我用名称输出结果,并以整数排序

!/usr/bin/env/python
您可以使用regex和
heapq

import re
import heapq

f = [i.strip('\n') for i in open('filename.txt')]
new_f = [re.findall("(?<=\d{1,}\.\s)[a-zA-Z0-9]+", i) for i in f]
def heapqueue_sort(numbers):
    l = []
    heapq.heapify(l)
    for i in numbers:
        heapq.heappush(l, i)
    return [heapq.heappop(l) for i in range(len(l))]
final_data = [new_f[0]].extend(heapqueue_sort(map(int, new_f[1:]))]
print(final_data)
重新导入
进口heapq
f=[i.strip('\n')表示打开的i('filename.txt')]

新建\u f=[re.findall(”(?也发布你的代码尝试。你能展示你已经尝试了什么吗?你能提供一个吗?你期望的输出是什么?你实际的输出是什么?你能展示给我们而不是告诉我们吗?这个问题目前很广泛。这是整个文件,还是只是其中的一部分?是的,我可以发布我的代码,我能够分离字符串和整数。现在有了按优先级队列顺序对整数进行排序。下面是我的代码#!/usr/bin/env/python import sys import os def heapsort(iterable):file=[]用于iterable中的值:heappush(h,value)return[heapop(h)for i in range(len(file))]def main():h=[]infle=open(sys.argv[1],“rb”)str=infle.readline()用于infle中的行:用于行中的nbr.split():h.append(nbr)print str print h infle.close()main()你们在哪里把数值输入数字?你们能解释一下吗please@Gloria_2015我不知道你的意思。你指的是函数调用吗?是的,你能解释一下int和new_f的映射在这个函数中是如何工作的吗method@Gloria_2015map采用一个特定的函数,在本例中为整数函数,并将其应用于列表中的每个元素。
new\u f
搜索文件中小数点后的整数值。
import re
import heapq

f = [i.strip('\n') for i in open('filename.txt')]
new_f = [re.findall("(?<=\d{1,}\.\s)[a-zA-Z0-9]+", i) for i in f]
def heapqueue_sort(numbers):
    l = []
    heapq.heapify(l)
    for i in numbers:
        heapq.heappush(l, i)
    return [heapq.heappop(l) for i in range(len(l))]
final_data = [new_f[0]].extend(heapqueue_sort(map(int, new_f[1:]))]
print(final_data)