[英]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
然后您可以對該列表執行任何操作。
人們可以用特殊對待的第一行(在這種情況下忽略它) 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.