본문 바로가기

Python

(13)
list 안에 dict 꺼내서 xlsx로 출력하기 import pandas as pd def main(): population = [ { "서울특별시": 9414, "부산광역시": 3306, "경기도": [ { "수원시": 1191, "고양시": 1077 } ] } ] population_sort = {} for item in population: for location, val in item.items(): if location == "경기도": for sub_item in item["경기도"]: for city, num in sub_item.items(): population_sort[city] = num else: population_sort[location] = val print(population_sort) # dict를 xlsx로 출력하기 d..
json.dump json.dump(데이터 저장된 변수, 파일 포인터, ensure_ascii=False, indent=4) ensure_ascii=False 파일 작성된 그대로 써준다. True는 한글일 경우 16진수로 써주기 때문에 False로 입력해야 한다. * 글자가 깨지면 atom에서 인코딩을 EUC-KR로 바꿔주기 indent=4 들여쓰기해서 예쁘기 정렬하기 sort_keys=True 정렬해서 출력하기. 딕셔너리 키를 기준으로
from () import () 차이 import () as () from (모듈명) import(함수명/클래스명) from (패키지명) import (모듈명) -> 코드에 라이브러리 따로 작성하지 않아도 된다 -> (함수) 자리에 * 사용하면 모든 함수 사용한다는 뜻이다. 해당 라이브러리의 모든 함수를 사용할 수 있다. import (라이브러리/모듈) as (별칭) import (패키지명) as (별칭) -> 코드에 (변수) 항상 작성해야 한다. -> 파이썬에 이미 만들어진 라이브러리의의 파일들을 사용할 수 있다. -> 라이브러리를 호출하고, 모듈을 별칭으로 정해서 해당 모듈의 함수와 클래스를 사용한다. -> dir(라이브러리) : 해당 라이브러리가 지원하는 함수를 확인 할 수 있다. import pandas as pd m = pd.head() pd.소모듈이름.함수이..
Python HTML BeautifulSoup URL 뒤에 robots.txt https://wanderlog.com/robots.txt Beautiful Soup documentation https://www.crummy.com/software/BeautifulSoup/bs4/doc/# 맥은 기본적으로 막고 있어서 해지하는 코드 입력 terminal
Python: function class module package library function < class < module < package < library Module (파일) 프로그램에서 함수와 클래스를 파일로 만들어 사용한다. 파이썬에 내장되어 있어 가져와 사용할 수 있고, 직접 만들 수도 있다. Package(폴더) 서브패키지와 관련있는 모듈끼리 한 디렉토리에 모아 놓는다. 계층적인 디렉토리 구조를 가지고 있다. Library 함수나 모듈이 모인 집합체이다. 외부 라이브러리 : pandas(데이터 분석), numpy(다차원 배열과 행렬), Matplotlib(시각화), Scikit-learn 등 설치해야 한다: pip install 라이브러리명
Module 모듈 모듈이란? 함수나 변수 또는 클래스를 모아 놓은 파일, 코드 재사용 가능 사용 방법1 import 모듈명 모듈명.모듈안에서 만든 함수명(파라미터) 모듈명.모듈안에서 만든 변수명 -> 변수의 값이 출력된다. 사용 방법2 from 모듈명 import 모듈안에서 만든 함수명, 추가로 불러올 수 있음 이름 변경/참조 모듈변경 import 모듈명 as 변경할모듈명 -> 모듈명을 바꿔서 사용한다. 모듈명에 입력한 모듈을 참고한다는 뜻 함수명변경 from 모듈명 import 함수명 as 변경할 함수명 from 모듈 import * 모듈에 있는 모든 함수를 사용한다. -> 특정함수가 어느 모듈에 있는건지 확인어렵고, 필요하지 않은 함수들을 불러오는 경우가 있어 사용을 잘 안한다.
Topic-Model system from sklearn.decomposition import LatentDirichletAllocation from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer spam_header = 'spam\t' no_spam_header = 'spam\t' documents = [] with open('./smsspamcollection/SMSSpamCollection') as file_handle: for line in file_handle: if line.startswith(spam_header): documents.append(line[len(sp..
[Codecademy] 12. File Input and Output [Codecademy] 12. File Input and Outputwrite-only mode ("w")read-only mode ("r")read and write mode ("r+")append mode ("a"), which adds any new data you write to the file to the end of the file.flush()출력 할 내용을 모았다가 한번에 출력한다. out이 화면에 출력되는 시점과 명령을 내린 시점이 차이가 나기때문에 flush 명령어를 사용한다. my_list = [i ** 2 for i in range(1, 11)] my_file = open("output.txt", "w") for value in my_list: my_file.write(str(val..
[Codecademy] 11-1. Introduction to Classes [Codecademy] 11-1. Introduction to Classes Python is an object-oriented programming language, which means it manipulates programming constructs called objects. You can think of an object as a single data structure that contains data as well as functions; the functions of an object are called its methods. 파이썬은 객체 지향 프로그래밍 언어입니다. 즉, 객체라는 프로그래밍 구성을 조작합니다. 객체는 함수뿐만 아니라 데이터도 포함하는 단일 데이터 구조라고 생각할 수 있습..
[Codecademy] 10-2. INTRODUCTION TO BITWISE OPERATORS [Codecademy] 10-2. INTRODUCTION TO BITWISE OPERATORS bin() takes an integer as input and returns the binary representation of that integer in a string. (Keep in mind that after using the bin function, you can no longer operate on the value like a number.) int() 2,8,16진법을 10진법으로 변환하기bin() 10진법을 2진법으로 변환하기oct() 10진법을 8진법으로 변환하기dec() hex() 10진법을 16진법으로 변환하기 print bin(1)print bin(2)print bin(3)print..
[Codecademy] 10-1. Advanced Topics in Python [Codecademy] 10-1. Advanced Topics in Python Anonymous Functions 익명함수lambda는 한 줄로 함수를 작성하는 방식으로 lambda expression이라고 부른다. 함수를 간편하게 작성할 수 있어서 다른 함수의 인수로 넣을 때 주로 사용한다. --- languages = ["HTML", "JavaScript", "Python", "Ruby"]print filter(lambda x: x == "Python", languages)--- squares = [x ** 2 for x in range(1, 11)]print filter(lambda x: x >= 30 and x I am another secret message!
[Codecademy] 9. Dictionary [Codecademy] 9. Dictionary evens_to_50 = [i for i in range(51) if i % 2 == 0]print evens_to_50 doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 == 0] even_squares = [x ** 2 for x in range(1, 11) if (x ** 2) % 4 == 0] print even_squares --- cubed number 3승 수
[Codecademy] 8. EXAM STATISTICS [Codecademy] 8. EXAM STATISTICS grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def print_grades(grades_input): for grade in grades_input: print grade def grades_sum(scores): total = 0 for score in scores: total += score return total def grades_average(grades_input): sum_of_grades = grades_sum(grades_input) average = sum_of_grades / float(len(grades_input)) return average def ..