728x90
1. 파일 다루기
파일 전체적으로 읽기
with open(‘data.txt’) as file:
content = file.read()
줄 단위로 읽기
contents = []
with open(‘data.txt’) as file:
for line in file:
contents.append(line)
파일의 모드(쓰기)
# 쓰기 (Write) 모드로 파일을 연다
with open(‘data.txt’, ‘w’) as file:
file.write(‘Hello’)
파일의 모드(읽기)
# 쓰기 (Write) 모드로 파일을 연다
with open(‘data.txt’, ‘r’) as file:
content = file.read()
2. 데이터 구조 다루기
리스트 vs 튜플
튜플 | 리스트 | |
공통점 | 순서가 있는 원소들의 집합 | |
차이점 | 각 원소의 값을 수정할 수 없음 원소의 개수를 바꿀수 없음 |
각 원소의 값을 수정할 수 있다 원소의 개수를 바꿀수 있다 |
튜플의 형태
hello = (‘안녕하세요’, ‘hello’, ‘bonjour’)
apple = (‘사과’, ‘apple’, ‘pomme’)
red = (‘빨갛다’, ‘red’, ‘rouge’)
튜플 예제
# 단어,빈도수로 이뤄진 텍스트 파일에서 튜플로 구성된 리스트를 리턴하는 함수
def import_as_tuple(filename):
tuples = []
with open(filename) as file:
for line in file:
split = line.strip().split(',') # strip : 줄바꿈 문자를 없애주는 함수
word = split[0] # 단어
freq = split[1] # 빈도수
new_tuple = (word, freq) # 튜플에 넣어 리스트로 append
tuples.append(new_tuple)
return tuples
3. 리스트 컴프리헨션
for문을 리스트 안에 입력하면 새로운 리스트를 코드 한 줄로 간결하게 생성할 수 있다.
즉, 한 줄 명령어로 데이터를 다룰 수 있다.
리스트 컴프리헨션 예제
# 해당 prefix에 맞는 단어 고르기
words = [
'apple',
'banana',
'alpha',
'bravo',
'cherry',
'charlie',
]
def filter_by_prefix(words, prefix):
return [n for n in words if n[0]==prefix] # 리스트 컴프리헨션 사용 지점
a_words = filter_by_prefix(words, 'a')
4. 튜플 정렬
튜플 정렬 예제
# 해당 단어의 빈도수를 담은 리스트 선언
pairs = [
('time', 8),
('the', 15),
('turbo', 1),
]
#(단어, 빈도수) 쌍으로 이루어진 튜플을 받아, 빈도수를 리턴합니다.
def get_freq(pair):
return pair[1]
#(단어, 빈도수) 꼴 튜플의 리스트를 받아, 빈도수가 낮은 순서대로 정렬하여 리턴합니다.
def sort_by_frequency(pairs):
return sorted(pairs, key=get_freq) # key에 pairs를 직접 접근할 수 없다. why? tuple (key=pairs[1] => X)
# 따로 데이터를 처리하는 함수를 만들어주거나 or key = lambda로 접근한다
'python' 카테고리의 다른 글
[python] string.punctuation (2) | 2022.03.30 |
---|---|
[python] 딕셔너리/JSON/집합 (0) | 2022.01.29 |
[python] str.startswith / str.endswith (0) | 2022.01.28 |
[python] deque (0) | 2021.10.24 |
[python] sort/sorted 함수 알아보기 (0) | 2021.10.20 |
댓글