我想使速度更快,我不是一个优秀的编码人员,只想学习。该程序读取以逗号分隔的普通艺术家的段落。用户输入所需艺术家的姓名,程序搜索段落以查找所有相关艺术家,并将它们按最常见到最不常见的顺序排序。艺术家的文本文件很大,只有600kb的文本,所以也许这就是它缓慢的原因。
class ArtistSuggester:
fileName = "list_of_artists.txt"
arrayOfLists = []
artist = input("Enter Artist Name: ")
@classmethod
def make_array(cls):
# sets text to 2D-array
f = open(cls.fileName, 'r', encoding="utf8")
curr_par = f.read().split("\n")
for line in curr_par:
cls.arrayOfLists.append(line.split(","))
@classmethod
def get_locations(cls):
# searches array for given artist and returns array with areas where the artist was found
locations = []
for x in range(0, len(cls.arrayOfLists)):
for y in range(0, len(cls.arrayOfLists[x])):
if cls.arrayOfLists[x][y] == cls.artist:
locations.append(x)
return locations
@staticmethod
def search_array_for_artist(the_list, artist):
# searches given array for the given artist's name and returns the position
# if found nothing returns negative number to symbolize non-existence
pos = 0
for x in range(0, len(the_list)):
if the_list[x] == artist:
pos = x
break
else:
pos = -1
return pos
@classmethod
def ordered_suggestion_list(cls):
# makes the final suggestion list in correct order
# makes two arrays, one with the names and the other with the counts of each throughout the text file.
check = cls.get_locations()
final_list = cls.arrayOfLists[check[0]]
final_list.remove(cls.artist)
count = [1] * int(len(final_list))
for x in range(1, len(check)):
for y in range(0, len(cls.arrayOfLists[check[x]])):
if cls.arrayOfLists[check[x]][y] == cls.artist:
continue
elif cls.search_array_for_artist(final_list, cls.arrayOfLists[check[x]][y]) > 0:
count[cls.search_array_for_artist(final_list, cls.arrayOfLists[check[x]][y])] += 1
else:
final_list.append(cls.arrayOfLists[check[x]][y])
count.append(1)
# makes a dict based off the count and names list to combine values to the keys
combined_list = dict(zip(final_list, count))
new_list = []
for key, value in sorted(combined_list.items(), key=lambda x: x[1], reverse=True):
new_list.append(key)
print(new_list)