繁体   English   中英

Python读取文件问题

[英]Python reading file problems

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一样),每个字母都有多个字母。 我必须能够通过这个程序算出每个折扣多少。 我对此很陌生,因此如果所创建的编码错误,请多多包涵。 只是想知道是否有人能指出我正确的方向,如何在第二行中拉出这些字母并计算它们。 然后,我必须对这些字母进行数学运算,但我希望自己解决。

数据样本:

GTSDF60000
ADCBCBBCADEBCCBADGAACDCCBEDCBACCFEABBCBBBCCEAABCBB
*

您不读取文件的内容。 为此,请在打开的文件上使用.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 -statement会为您关闭文件(因此,您无需使用.close() -方法。由于只需要第二行的内容,因此您可以直接选择该行:

    content = g.readlines()[1]

.readlines()不会.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)

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

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
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))

您可能需要检查正则表达式 ,以防需要更复杂的模式。

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

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

人们可以用特殊对待的第一行(在这种情况下忽略它) nexttry: 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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM