简体   繁体   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)

Hello, wondered if anyone could help me , I'm having problems here. 您好,想知道是否有人可以帮助我,我在这里遇到问题。 I have to read in a file of which contains 3 lines. 我必须阅读一个包含3行的文件。 First line is no use and nor is the 3rd. 第一行没有用,第三行也没有。 The second contains a list of letters, to which I have to pull them out (for instance all the As all the Bs all the Cs all the way upto G) there are multiple letters of each. 第二个包含一个字母列表,我必须将它们拉出(例如,所有的B到C一直到G一样),每个字母都有多个字母。 I have to be able to count how many off each through this program. 我必须能够通过这个程序算出每个折扣多少。 I'm very new to this so please bear with me if the coding created is wrong. 我对此很陌生,因此如果所创建的编码错误,请多多包涵。 Just wondered if anyone could point me in the right direction of how to pull out these letters on the second line and count them. 只是想知道是否有人能指出我正确的方向,如何在第二行中拉出这些字母并计算它们。 I then have to do a mathamatical function with these letters but I hope to work that out for myself. 然后,我必须对这些字母进行数学运算,但我希望自己解决。

Sample of the data: 数据样本:

GTSDF60000
ADCBCBBCADEBCCBADGAACDCCBEDCBACCFEABBCBBBCCEAABCBB
*

You do not read the contents of the file. 您不读取文件的内容。 To do so use the .read() or .readlines() method on your opened file. 为此,请在打开的文件上使用.read().readlines()方法。 .readlines() reads each line in a file seperately like so: .readlines()读取文件中的每一行,如下所示:

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

since it is good practice to directly close your file after opening it and reading its contents, directly follow with: 由于优良作法是在打开文件并阅读其内容后直接关闭文件,因此请直接执行以下操作:

g.close()

another option would be: 另一个选择是:

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

the with -statement closes the file for you (so you don't need to use the .close() -method this way. Since you need the contents of the second line only you can choose that one directly: with -statement会为您关闭文件(因此,您无需使用.close() -方法。由于只需要第二行的内容,因此您可以直接选择该行:

    content = g.readlines()[1]

.readlines() doesn't strip a line of is newline(which usually is: \\n ), so you still have to do so: .readlines()不会.readlines()行(通常是\\n ),因此您仍然必须这样做:

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

The .count() -method lets you count items in a list or in a string. .count()方法可让您对列表或字符串中的项目进行计数。 So you could do: 因此,您可以执行以下操作:

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

this can be made more efficient by using a dictionary-comprehension: 通过使用字典理解,可以提高效率:

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

at last you can get the highest score and print it: 最后,您可以获得最高分并打印出来:

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

.values() returns the values of a dictionary and max, well, returns the maximum value in a list. .values()返回字典的值,而max返回列表中的最大值。

Thus the code that does what you're looking for could be: 因此,执行您要查找的代码可能是:

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)

To count the occurrences of each letter I used a dictionary instead of a list. 为了计算每个字母的出现次数,我使用了字典而不是列表。 With a dictionary, you can access each letter count later on. 使用字典,以后可以访问每个字母数。

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)

Outputs 产出

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

You might want to check regular expressions in case you need some more complex pattern. 您可能需要检查正则表达式 ,以防需要更复杂的模式。

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

This will show you the second line of that file. 这将显示该文件的第二行。 It will extend arrayList then you can do whatever you want with that list. 它将扩展arrayList然后您可以对该列表执行任何操作。

One can treat the first line specially (and in this case ignore it) with next inside try: except StopIteration: . 人们可以用特殊对待的第一行(在这种情况下忽略它) nexttry: except StopIteration: In this case, where you only want the second line, follow with another next instead of a for loop. 在这种情况下,如果只需要第二行,请紧跟着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