2016-10-11 1 views
0

내가 레스토랑 이름의 파일을 가지고 있고 그 파일을 검색하여 "이탈리아어"와 같은 특정 문자열을 찾아야한다고 가정 해보십시오. 파일에서 문자열을 검색하고 같은 문자열을 가진 레스토랑 수를 출력하면 코드가 어떻게 보이나요?파이썬에서 파일 검색하기

f = open("/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt", "r") 
content = f.read() 
f.close() 
lines = content.split("\n") 
with open("/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt") as f: 
     print ("There are", len(f.readlines()), "restaurants in the dataset") 
with open("/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt") as f: 
     searchlines = f.readlines() 
    for i, line in enumerate(searchlines): 
    if "GREEK" in line: 
     for l in searchlines[i:i+3]: print (l), 
     print 
+0

파일 형식에 대한 정보는 무엇입니까? – BLang

+0

마치 숙제로 보입니다. –

+0

@BLang 파일은 한 줄에 하나의 레스토랑 이름으로 서식이 지정되어 있으며 다른 내용은 포함되어 있지 않습니다. – Normality

답변

2

특정 단어에 대한 검색을 수행

from collections import Counter 
from string import punctuation 

f_name = "/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt" 


with open(f_name) as f: 
    # sum(1 for _ in f) -> counts lines 
    print ("There are", sum(1 for _ in f), "restaurants in the dataset") 
    # reset file pointer back to the start 
    f.seek(0) 
    # get count of how many times each word appears, at most once per line 
    cn = Counter(word.strip(punctuation).lower() for line in f for word in set(line.split())) 
    print(cn["italian"]) # no keyError if missing, will be 0 

우리가 사용 set(line.split()) 단어가 특정 식당을 두 번 출연 그렇다면, 우리는 한 번만 계산할 것입니다. 정확히 일치하는 부분을 찾습니다. foo과 같은 부분을 foobar에 일치 시키려면 여러 단어를 효율적으로 찾을 수있는 데이터 집합을 만드는 것이 더 복잡 할 것입니다. 당신이 정확히 일치를 원하는 경우

f_name = "/home/ubuntu/ipynb/NYU_Notes/2-Introduction_to_Python/data/restaurant-names.txt" 

with open(f_name) as f: 
    print ("There are", sum(1 for _ in f), "restaurants in the dataset") 
    f.seek(0) 
    sub = "italian" 
    count = sum(sub in line.lower() for line in f) 

, 당신이 필요합니다 : 당신이 정말로 하나 개의 단어를 계산하려면

은 당신이해야 할 모든 문자열이 한 줄에 나타납니다 합을 얼마나 많은 시간을 사용하는 것입니다 논리를 다시 분할하거나 단어 경계가있는 정규식을 사용하십시오.

-1

파일을 문자열로 입력했습니다.
그런 다음 문자열의 count 메소드를 사용하십시오.
코드 : 당신은 모든 단어는 다음 카운터 딕셔너리를 사용하여 셀 수

#Let the file be taken as a string in s1 
print s1.count("italian")