Python을 사용하여 text_file.txt에서 a, b 및 c의 값을 추출하고 싶습니다.
text_file.txt
$This Script is written for value extraction$
a = 2.88
b = 3.9
c = 4.9 $this is a value for C$
d = 3.2 $not require for the program$
다음 코드는 파일에서 변수 (목록, 사전 및 집합과 호환 가능)를 검색하고 요청에 따라 지역 변수로 추가합니다.
import ast
vars = {}
# Open file for reading
with open('file.txt', 'r') as f:
lines = f.readlines()
for l in lines:
try:
# Find comment begining
end = l.index('$')
except ValueError:
# If no comment, set end to last char
end = len(l)
# Set the part to parse
assignment = l[:end]
# Try split assignment to the variable name and value
x = assignment.split('=')
# If it's assignment (splitted to two parts)
if 2 == len(x):
var, value = x
# Safe evaluate and add to dictionary
vars[var.strip()] = ast.literal_eval(value.strip())
# {'a': 2.88, 'b': 3.9, 'c': 4.9, 'd': 3.2}
print(vars)
# Set as local variables
for k,v in vars.items():
locals()[k] = v
# a: 2.88
print(f'a: {a}')
# b: 3.9
print(f'b: {b}')
# c: 4.9
print(f'c: {c}')
# d: 3.2
print(f'd: {d}')
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다