*args
구문을 함수 매개 변수 목록에 사용하면 함수의 튜플로 표시되는 여러 인수를 사용하여 함수를 호출 할 수 있습니다. 따라서 각 인수에 대해 프로세스를 수행하려면 루프를 만들어야합니다. 이처럼 :
from string import punctuation
# Make a translation table to delete punctuation
no_punct = dict.fromkeys(map(ord, punctuation))
def open_file(*filenames):
for filename in filenames:
print('FILE', filename)
with open(filename) as file:
text = file.read()
text = text.translate(no_punct).lower()
print(text)
print()
#test
open_file('Strawson.txt', 'BigData.txt')
또한 텍스트에서 모든 문장 부호를 제거하는 데 사용할 수있는 사전 no_punct
을 포함 시켰습니다. 각 파일이 자동으로 닫히도록 with
문을 사용했습니다. 당신이 기능을 "반환"각 파일의 처리 내용을 원하는 경우에 그 종료하는 기능을 알려주기 때문에
, 당신은 루프에 return
를 넣을 수 없습니다. 은 파일 내용을 목록에 저장하고 루프의 끝에서이를 반환 할 수 있습니다. 그러나 더 나은 옵션은 함수를 생성기로 변환하는 것입니다. Python yield
키워드를 사용하면 간단 해집니다. 다음은 시작하기위한 예입니다. 우리는 이미 모든 문장 부호를 제거하고 open_file
내부 소문자로 텍스트를 접는 있기 때문에 필요하지 않을 것 : 나는 create_tokens
에서 word.strip(punctuation).lower()
물건을 제거
def open_file(*filenames):
for filename in filenames:
print('FILE', filename)
with open(filename) as file:
text = file.read()
text = text.translate(no_punct).lower()
yield text
def create_tokens(*filenames):
tokens = []
for text in open_file(*filenames):
tokens.append(text.split())
return tokens
files = '1.txt','2.txt','3.txt'
tokens = create_tokens(*files)
print(tokens)
참고.
여기에는 실제로 두 가지 기능이 필요하지 않습니다. 모든 것을 하나로 결합 할 수 있습니다.
def create_tokens(*filenames):
for filename in filenames:
#print('FILE', filename)
with open(filename) as file:
text = file.read()
text = text.translate(no_punct).lower()
yield text.split()
tokens = list(create_tokens('1.txt','2.txt','3.txt'))
print(tokens)
어떻게 그 기능을 부르겠습니까? 여러 개의 파일 이름을 전달하려면 튜플을 반복하고 각 파일을 열고 처리해야합니다. –
나는이 함수를 어떻게 호출하는지 보여주기 위해 질문을 편집했다. 네가 방금 말한대로 어떻게하면 될까? @ PM2Ring – vvv12308
BTW,'.strip (chars)'메소드는 문자열의 시작과 끝에서 문자를 지우고, 지정된 문자가 아닌 char을 만나면 더 이상 가지 않습니다. 따라서'file.read(). strip (punctuation)'을 사용하면 파일의 시작과 끝에서 구두점 문자 만 제거됩니다. 너가 원하는게 그거야? 또는 전체 파일에서 모든 구두점을 제거 하시겠습니까? –