English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Google Speech API를 사용하여 Python에서 음성 인식

문서

NamedTuple은 collections 모듈 아래에 있는 또 다른 클래스입니다. 딕셔너리 타입의 객체와 마찬가지로 키를 포함하고, 특정 값에 매핑됩니다. 이 경우, 키와 인덱스를 사용하여 요소에 접근할 수 있습니다.

먼저 사용하기 전에 그를 수집 표준 라이브러리 모듈에 가져오는 것이 필요합니다.

import collections

이 섹션에서는 NamedTuple 클래스의 몇 가지 기능을 보여드리겠습니다.

NamedTuple 접근 방법을 사용할 수 있습니다.NamedTuple은 필드 이름을 속성으로 변환합니다. 따라서NamedTuple에서는 인덱스, 키와

메서드를 사용하여 값을 접근합니다. NamedTuple의 속성 값은 순서가 있습니다. 따라서 이를 사용하여 인덱스를 통해 접근할 수 있습니다.NamedTuple은 필드 이름을 속성으로 변환합니다. 따라서getattr()

예제 코드

import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
데이터를 가져올 수 있습니다.
e1 = Employee('Asim', 'Delhi', '25000')
e2 #두 인사를 추가합니다30000')
= Employee('Bibhas', 'Kolkata', '''
#getattr()를 사용하여 요소에 접근합니다1#getattr()를 사용하여 요소에 접근합니다 print('The City of e + e1#index를 사용하여 요소에 접근합니다 + , 'city') + e1[0]2[
])
#getattr()를 사용하여 요소에 접근합니다2#getattr()를 사용하여 요소에 접근합니다 print('The City of e + e2print('The name and salary of e + , 'city') + e2.name
.salary)1 The City of e2#getattr()를 사용하여 요소에 접근합니다 print('The City of e + ' and '1: ' + , 'city') + ' and '2getattr(e

출력 결과

0001, 'city')) 25: Asim와
0002The name과 salary of e 3: Bibhas와
00001 The City of e2하고 e

: 델리와 콜카타

NamedTuple 변환 과정

따라서 다른 셋을 NamedTuple 객체로 변환할 수 있는 몇 가지 방법이 있습니다. _make() 메서드는 리스트, 튜플 등과 같은 이터러블 객체를 NamedTuple 객체로 변환하는 데 사용됩니다.**연산자.

NamedTuple은 OrderedDict형 객체로 값을 반환할 수 있습니다. OrderedDict로 만들기 위해 _asdict() 메서드를 사용해야 합니다.

예제 코드

import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#values 목록을 Employee에
my_list = ['Asim', 'Delhi', '25000']
e1 = Employee._make(my_list)
print(e1)
#Dict to convert Employee
my_dict = {'name':'Bibhas', 'city' : 'Kolkata', 'salary' : '30000'}
e2 = Employee(**my_dict)
print(e2)
#Show the named tuple as dictionary
emp_dict = e1._asdict()
print(emp_dict)

출력 결과

Employee(name='Asim', city='Delhi', salary='25000')
Employee(name='Bibhas', city='Kolkata', salary='30000')
OrderedDict([('name', 'Asim'), ('city', 'Delhi'), ('salary', '25000')])

NamedTuple에 대한 몇 가지 다른 연산

다른 몇 가지 방법도 있습니다. 예를 들어 _fields()와 _replace() 메서드. _fields() 메서드를 사용하여 NamedTuple의 다른 필드를 확인할 수 있습니다. _replace() 메서드는 다른 값들을 대체하는 데 사용됩니다.

예제 코드

import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#Add an employees
e1 = Employee('Asim', 'Delhi', '25000')
print(e1)
print('The fields of Employee: ' + str(e1._fields))
#replace the city of employee e1
e1 = e1._replace(city='Mumbai')
print(e1)

출력 결과

Employee(name='Asim', city='Delhi', salary='25000')
The fields of Employee: ('name', 'city', 'salary')
Employee(name='Asim', city='Mumbai', salary='25000')
SQLite 튜토리얼