1

我有这个项目,我必须用 Python 编写代码,但对于一个初学者来说非常困难。基本上,我从来没有用过python编程,从昨天开始才开始用谷歌学习它,所以我想也许你们可以帮忙,因为我什至无法开始解决这个问题。

我得到了一个初始文本文件,我们称之为 input.txt,其中包含以下数据:

Thomas Hales
12 2345 
45 6780
63 3210
Peter Lebones
10 15430
11  1230
23 3450
John White
2 12130
11 32410
15 4520

在它们下面有给定的名称和数字。左栏中的数字只是用于此问题的标识号。右栏中的数字是人们在银行投资的金额。

我应该获取文本文件中的所有数据,以某种方式对其进行操作,然后创建一个名为 output.txt 的新文本文件(所有这些都由 python 运行的脚本完成),对于上面的示例,包含这个:

Thomas Hales 45
Peter Lebones 10
John White 11

到目前为止我所拥有的(但它根本不起作用。再加上一团糟,我是在某人的帮助下完成的,他也不知道他在做什么):

import sys
import subprocess
import re
import string


try:
    fread=open(sys.argv[1]).readlines()
except IOError:
    print "There is no file like that!"
    sys.exit()
except IndexError:
    print "There is no argumentum given"
alpha = string.ascii_letters
writeout=open("result.txt","w")
inputarray=fread.readlines()
for ... in inputarray: # not sure what goes in the "..." part
    array=inputarray.split('\n')
for i in range(len(array)-1):
    if array[i].isalpha():
    writeout.write(array[i]+" ")

fread.close()
writeout.close()

所以基本上,我得到了一个文本文件。然后,我应该为每个人选择他们的最高投资,并将左栏中的数字与所述最高投资相关联。然后我应该让脚本生成一个 output.txt,其中包含每个人的姓名和他们最高投资的“身份证号”。

4

4 回答 4

2

我假设当一行以数字开头时,我们有一个投资,否则就是一个名字。

每次找到一个名字时,写下以前的名字和最高的投资标识符:

with open(sys.argv[1]) as inputfile, open("result.txt","w") as outputfile:
    name = None
    investment_id = max_investment = 0
    for line in inputfile:
        if not line.strip(): continue  # skip empty lines

        if not line[:1].isdigit():  # name
            if name and investment_id: 
                # write previous name
                outputfile.write('{} {}\n'.format(name, investment_id))
            name = line.strip()
            investment_id = max_investment = 0

        else:
            id, investment = [int(i) for i in line.split()]
            if investment > max_investment:
                max_investment = investment
                investment_id = id

    if name and investment_id: 
        # write last name
        outputfile.write('{} {}\n'.format(name, investment_id))

对于您的示例输入,它写道:

Thomas Hales 45
Peter Lebones 10
John White 11
于 2013-04-12T15:10:21.677 回答
1
   with open("input.txt", "r") as inp, open("output.txt", "w") as out:
       data = inp.readlines()
       for i in xrange(0, len(data), 4):
           name = data[i].strip()
           maxi = 0
           true_code = 0
           for item in data[i+1: i+4]:
              code, bal = item.strip().split(" ")
              code, bal = int(code), int(bal)
              if bal >= maxi:
                  maxi = bal
                  true_code = code
           out.write("%s %s" %(name, true_code))
于 2013-04-12T15:24:17.543 回答
1

Perhaps this basic recipe for processing a file line by line will help get you started on the right foot.

import sys

file_name = sys.argv[1]

# This takes care of closing the file after we're done processing it.
with open(file_name) as file_handle:

    # Once we have a file handle, we can iterate over it.
    for line in file_handle:

        # This is where your real programming logic will go.
        # For now, we're just printing the input line.
        print line,

I suspect you might also find split() to be useful, because it will allow you to break the numeric lines apart. For example, you could try this to experiment with how it works:

parts = line.split()
print parts
于 2013-04-12T15:13:16.533 回答
1

using the python re module may give you a nice launching platform, simply breaking down the lines into something you can iterate over.

>>> results = re.findall("(\w+) (\w+)",buff,re.S)
[('Thomas', 'Hales'), ('12', '2345'), ('45', '6780'), ('63', '3210'), ('Peter', 'Lebones'), ('10', '15430'), ('23', '3450'), ('John', 'White'), ('2', '12130'), ('11', '32410'), ('15', '4520')]
于 2013-04-12T15:13:56.433 回答