этот код можно усовершенствовать чтобы он работал быстрее? import os import sys def…
- User
этот код можно усовершенствовать чтобы он работал быстрее?
import os import sys
def dp(content): content = content.replace(" ", "") return content def dp2(content): content = content.replace("'", "") return content def dp3(content): content = content.replace("+", "") return content folder_path = 'numbers' arg = sys.argv[1]
files = os.listdir(folder_path)
files = [arg]
folder_path2 = 'base' files2 = os.listdir(folder_path2)
for file_name in files: if file_name.endswith(".txt"): print(file_name) file_path = os.path.join(folder_path, file_name) with open(file_path, 'r', encoding="utf-8") as file: lines = file.read() lines=str(lines).split('\n') for line in lines: part=str(line).split('\t') part = list(filter(None, part)) if len(part)>1: for file_name2 in files2: if file_name2.endswith(".txt"): file_path2 = os.path.join(folder_path2, file_name2) with open(file_path2, 'r', encoding="utf-8") as file2: lines2 = file2.read() lines2=str(lines2).split('\n') for line in lines2: if str(part[0]) in line: line=line.split(',') line[0] = part[1] # print(line) with open('out/'+file_name2, 'a+', encoding="utf-8") as file: file.write(dp3(dp2(dp(str(line)[1:-1])))+'\n') break
- Assistant
Вот несколько способов усовершенствования данного кода, чтобы он работал быстрее:
-
Замените циклы на генераторы списков: вместо циклов for используйте генераторы списков с использованием функции map(). Например, вместо строк:
lines = file.read() lines=str(lines).split('\n')примените:
lines = file.read().split('\n') -
Замените функции dp(), dp2() и dp3() на одну функцию, которая применяет все замены одновременно.
-
Используйте множества для проверок вхождения вместо циклов for с условием if. Создайте множество, содержащее элементы lines2, и затем используйте оператор in для выполнения проверок. Например, вместо:
for line in lines2: if str(part[0]) in line: # ...примените:
-
- User
перепиши в одну функцию
def dp(content): content = content.replace(" ", "") return content def dp2(content): content = content.replace("'", "") return content def dp3(content): content = content.replace("+", "") return content
- Assistant
Вот переписанный код с функциями dp(), dp2() и dp3() объединенными в одну функцию:
def process_content(content): content = content.replace(" ", "") content = content.replace("'", "") content = content.replace("+", "") return contentВызов данной функции будет производить все замены одновременно.
- User
замени пробелы табуляцию точками , символ . for file_name in files: if file_name.endswith(".txt"): print(file_name) file_path = os.path.join(folder_path, file_name) with open(file_path, 'r', encoding="utf-8") as file: lines = file.read() lines = str(lines).split('\n') lines = set(lines) for line in lines: part = str(line).split('\t') part = list(filter(None, part)) if len(part)>1: for file_name2 in files2: if file_name2.endswith(".txt"): file_path2 = os.path.join(folder_path2, file_name2) with open(file_path2, 'r', encoding="utf-8") as file2: lines2 = file2.read() lines2 = str(lines2).split('\n') lines2 = set(lines2) for line2 in lines2: if str(part[0]) in line2: line2 = line2.split(',') line2[0] = part[1] # print(line) with open('out/'+file_name2, 'a+', encoding="utf-8") as file: file.write(dp(str(line2)[1:-1])+'\n') break
- Assistant
Вот переписанный код, где пробелы, табуляция и точки заменены символом точки ".":
def process_content(content): content = content.replace(" ", ".") content = content.replace("\t", ".") content = content.replace(".", "") return content for file_name in files: if file_name.endswith(".txt"): print(file_name) file_path = os.path.join(folder_path, file_name) with open(file_path, 'r', encoding="utf-8") as file: lines = file.read() lines = str(lines).split('\n') lines = set(lines) for line in lines: part = str(line).split('\t') part = list(filter(None, part)) if len(part) > 1: for file_name2 in files2: if file_name2.endswith(".txt"): file_path2 = os.path.join(folder_path2, file_name2) with open(file_path2, 'r', encoding="utf-8") as file2: lines2 = file2.read() lines2 = str(lines2).split('\n') lines2 = set(lines2) for line2 in lines2: if str(part[0]) in line2: line2 = line2.split(',') line2[0] = part[1] # print(line) with open('out/'+file_name2, 'a+', encoding="utf-8") as file: file.write(process_content(str(line2)[1:-1])+'\n') break
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.