본문 바로가기
공부/파이썬

python Data structures 8.4 list

by 남오공 2022. 1. 15.
728x90

사진이 없어서 허전하길래 올림

 

 

문제

 

8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

You can download the sample data at http://www.py4e.com/code3/romeo.txt

 

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line=line.split()
    for word in line:
        word=word.strip()
    	
        if word in lst:
            continue
        else:
            lst.append(word)

lst.sort()         
print(lst)

 

문제

 

8.5 Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line:

From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008

You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end.

Hint: make sure not to include the lines that start with 'From:'. Also look at the last line of the sample output to see how to print the count.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txt

 

 

fname = open('mbox-short.txt')
count = 0

for line in fname:
    line.rstrip()
    word=line.split(' ')
    if 'From' in line:
        count= count +1 
        print(word[1])

print("There were", count, "lines in the file with From as the first word")

위와 같이 작성했더니 27줄만 떠야되는데 54줄이 뜨는 문제가 발생함 

뭐가 문제일까 고민해보던 찰나 

fname = input("Enter file name: ")
if len(fname) < 1:
	fname = "mbox-short.txt"

fh = open(fname)
count=0
for line in fh:
	if not line.startswith("From "):
		continue
	line=line.split()
	count+=1
	print(line[1])

print("There were", count, "lines in the file with From as the first word")

이 코드로 성공 

'공부 > 파이썬' 카테고리의 다른 글

평균,분산, 표준편차 함수 코드  (0) 2022.02.07
dataframe series  (0) 2022.01.24
Python Data Structures 3주차  (0) 2022.01.14
파이썬의 다양한 string 함수 예시  (0) 2022.01.14
python data structures 1주차 -string  (0) 2022.01.14

댓글