Python读取文件问题

时间:2015-01-21 21:57:29

标签: python python-3.x

highest_score = 0
g = open("grades_single.txt","r")
arrayList = []
for line in highest_score:
    if float(highest_score) > highest_score:
       arrayList.extend(line.split())
g.close()

print(highest_score)

您好,想知道是否有人可以帮助我,我在这里遇到问题。我必须在一个包含3行的文件中读取。第一行是没用的,也不是第三行。第二个包含一个字母列表,我必须把它们拉出来(例如所有的所有B都是所有的C一直到G)每个都有多个字母。我必须能够通过这个程序计算每个人的数量。我对此非常陌生,所以如果创建的代码错误,请耐心等待。只是想知道是否有人能指出我如何在第二行拉出这些字母并计算它们的正确方向。然后我必须用这些字母做一个mathamatical函数,但我希望能为自己解决这个问题。

数据样本:

GTSDF60000
ADCBCBBCADEBCCBADGAACDCCBEDCBACCFEABBCBBBCCEAABCBB
*

5 个答案:

答案 0 :(得分:2)

您没有阅读该文件的内容。为此,请在打开的文件上使用.read().readlines()方法。 .readlines()分别读取文件中的每一行:

g = open("grades_single.txt","r")
filecontent = g.readlines()

因为在打开文件并阅读其内容后直接关闭文件是一种好习惯,请直接按照:

g.close()

另一种选择是:

with open("grades_single.txt","r") as g:
    content = g.readlines()

with - 语句会为您关闭文件(因此您不需要以这种方式使用.close() - 方法。 由于您只需要第二行的内容,您可以直接选择该内容:

    content = g.readlines()[1]

.readlines()不会删除一行换行符(通常是:\n),所以你仍然必须这样做:

    content = g.readlines()[1].strip('\n')

.count() - 方法可让您计算列表或字符串中的项目。所以你可以这样做:

dct = {}
for item in content:
    dct[item] = content.count(item)

使用词典理解可以提高效率:

dct = {item:content.count(item) for item in content}

最后你可以获得最高分并打印出来:

highest_score = max(dct.values())
print(highest_score)

.values()返回字典的值,而max,则返回列表中的最大值。

因此,执行您正在寻找的代码可能是:

with open("grades_single.txt","r") as g:
    content = g.readlines()[1].strip('\n')

dct = {item:content.count(item) for item in content}

highest_score = max(dct.values())
print(highest_score)

答案 1 :(得分:0)

为了计算每个字母的出现次数,我使用了字典而不是列表。使用字典,您可以稍后访问每个字母计数。

d = {}
g = open("grades_single.txt", "r")
for i,line in enumerate(g):
    if i == 1:
        holder = list(line.strip()) 
g.close()

for letter in holder:
    d[letter] = holder.count(letter)

for key,value in d.iteritems():
    print("{},{}").format(key,value)

输出

A,9
C,15
B,15
E,4
D,5
G,1
F,1

答案 2 :(得分:0)

import re


# opens the file in read mode (and closes it automatically when done)
with open('my_file.txt', 'r') as opened_file:

    # Temporarily stores all lines of the file here.
    all_lines_list = []

    for line in opened_file.readlines():
        all_lines_list.append(line)

    # This is the selected pattern.
    # It basically means "match a single character from a to g"
    # and ignores upper or lower case
    pattern = re.compile(r'[a-g]', re.IGNORECASE)

    # Which line i want to choose (assuming you only need one line chosen)
    line_num_i_need = 2

    # (1 is deducted since the first element in python has index 0)
    matches = re.findall(pattern, all_lines_list[line_num_i_need-1])

    print('\nMatches found:')
    print(matches)
    print('\nTotal matches:')
    print(len(matches))

如果您需要更复杂的模式,可能需要检查regular expressions

答案 3 :(得分:0)

highest_score = 0
arrayList = []
with open("grades_single.txt") as f:
    arraylist.extend(f[1])
print (arrayList)

这将显示该文件的第二行。它将扩展arrayList,然后您可以使用该列表执行任何操作。

答案 4 :(得分:0)

可以在next内使用try: except StopIteration:特别处理第一行(在这种情况下忽略它)。在这种情况下,只需要第二行,请使用其他next代替for循环。

with open("grades_single.txt") as f:
    try:
        next(f)  # discard 1st line
        line = next(f)
    except StopIteration:
        raise ValueError('file does not even have two lines')

# now use line
相关问题