
with open("file.txt") as f:
for line in f:
for word in f:
if word == 'President':
print('a')
텍스트 파일에 'president'라는 단어가 4번 있어도 아무 것도 인쇄되지 않습니다. 어떻게 확인하게 할 수 있나요?
내 텍스트 파일은 다음과 같습니다.
President Kacey Genicke
President Alexandra Twomey
President Aldous Graddell
President Bernie Jenicek
Officer Cyrill Vernazza
Officer Sutton Spier
Officer Isabella Seer
Officer Abbey Holdforth
Faculty Officer Lennie Lomaz
Faculty Officer Brant Howle
Faculty Officer Dionysus Summerbell
Faculty Officer Calhoun Duguid
Faculty Officer Tremain Arnaez
Faculty Officer Mirabella Trathan
Faculty Officer Dex Darcy
내 출력이 다음과 같기를 원합니다.
Kacey Genicke
Alexandra Twomey
Aldous Graddell
Bernie Jenicek
나는 이것을 시도했다 :
with open("file.txt") as f:
for line in f:
if 'President' in line:
print(line[10])
이것은 나에게 각 대통령의 첫 번째 편지를 제공합니다.
답변1
내부 루프 for word in f:
는~ 아니다반복하다"단어"for line in f
한 줄에 있지만 파일 줄을 소비하는 것과 동일합니다 .f
.
한 줄 안에 단어가 포함되어 있는지 확인하려면 'President'
다음이 필요합니다.
with open("file.txt") as f:
for line in f:
if 'President' in line:
print('a')
President
접두사가 제거된 단어 로 시작하는 행만 인쇄하려면 다음을 수행하십시오 .
with open("file.txt") as f:
for line in f:
if line.startswith('President'):
print(line.replace('President', '').strip())
답변2
우선, 나는 그것이 당신의 들여쓰기라고 생각합니다. 다음을 시도해 볼 수 있습니다.
with open('file.txt') as f:
count = 0
for line in f:
columns = line.split()
if len(columns) > 1 and 'President' in line:
print(columns[1], columns[2])
count += 1
print("There are ", count, "Presidents found")
President
특정 줄에 있는 경우 전체 줄을 인쇄해야 합니다 . 그런 다음 행을 열로 분할하고 그에 따라 열을 인쇄합니다.
그러나 그러한 경우에는 awk
Python을 사용하는 것이 훨씬 더 적절할 수 있습니다.
awk '/President/{c++; print $2,$3 } END { printf("There were %d Presidents found\n", c)}' file.txt
- 대통령 검색
- 카운터를 증가시킵니다. c.
- 두 번째 및 세 번째 열 인쇄
- 끝. 발견된 총 발생 횟수를 인쇄합니다.