세트

2017-11-21 1 views
-1
내가 성공하지 않고 잠재적 인 솔루션의 번호를 구현 한

와 값으로 목록 키와 값에 대한 튜플 사전을 업데이트. 그래서 나는 뭔가를 놓치고 있다고 생각합니다. 사전에서 값을 가져 와서 set(x)을 사용하려고했지만 작동하지 않습니다. 나는 운도없이 defaultdict을 사용하려고했습니다. 그리고 몇 가지 다른 옵션이 있습니다. 나는 내가 틀린 것을 시행하고 있다고 생각하지만 왜 그런지 잘 모르겠습니다. 어떤 제안? 여기 내 코드는 다음과 같습니다.세트

def open_file(f): 
    with open(input("Enter a file name: "),'r') as inf: 

    #while True: 

    #try: 
    # filename=input("Enter a filename: ").strip() 
     # fr=open(filename,"r") 
     # break 

    #except IOError: 
    # print("File "+filename+" does not exist. Please reenter") 


    # 
    lines = 0 
    while 1: 
     lines += 1 
     f = inf.readline() 
     f = f.lower() 
     f = re.sub(r'\b\w{1,2}\b', '', f) 
     f = "".join(i for i in f if i not in string.punctuation) 
     #print(lines, f) 
     #print(type(lines)) 
     print_list([f], lines) 

     if not f: 
      break 
    # 

def print_list(f, lines): 
    f = list(filter(None, f)) 
    for k in range(0, len(f)): 
    l = (f[k]) 
    l = l.strip(' ') 
    l = l.strip() 
    #print(l, lines) 
    #print(type(lines)) 
    read_data(l, lines) 
# 

def read_data(l, lines): 
    l = [l] 
    l = [x for x in l if x] 
    d = list(filter(None, l)) 
    print_list2(d, lines) 

def print_list2(f, lines): 
    global this_dic 

    for k in range(0, len(f)): 

    my_dictionary = f[k] 
    word = my_dictionary.split() 

    word = tuple(word) 

""""here is were the dictionary is created which is a regular dictionary 
for the keys and the values are a list. I want to change the list values 
into set values so that duplicates are removed. I am reading a file line 
by line and then creating a dictionary were the words appear and the line 
numbers they appear on. Later I will being asking for user input to 
search so if they enter "the" I will say the word "the" exists on line 
numbers 1, 3, 4, etc in this file"""" 

    for i in range(0, len(word)): 
     if word[i] not in this_dic: 
      this_dic[word[i]] = [lines] 
     else: 
      this_dic[word[i]].append(lines) 
다음은 올바른 방법입니다. 나는 위의 코드를 내가 시작한 것과 내가 해결책을 찾는 것의 차이점을 보여주는 방법으로 남겨두고있다.
for i in range(0, len(word)): 

     if word[i] not in this_dic: 
      this_dic[word[i]] = set() 
     this_dic[word[i]].add(lines) 


r = open_file(input("Press Any Key To Begin: You Will Enter A File Name During\ 
       The Next Prompt ")) 
def find_cooccurence(inp_str, D): 
    spit_str = inp_str.split() 
    d = set(tuple(D.values())) 

    print(spit_str, d) 
+1

당신은 실제로 원하는 출력을 표시 할 수 있습니다하세요? 내가 그 질문을 이해하는지 모르겠다. 게시 된 코드의 거대한 공백은 무엇입니까? 질문의 형식을 올바르게 지정하십시오. – roganjosh

+0

'dict'의 값을'list's에서'set's로 변경하고 싶습니까? 이 변경 사항을 계속 사용 하시겠습니까? 아니면이 속성으로 새 사전을 만들고 싶습니까? –

+0

이 아니면 값은 당신이 그것을 제공하기 전에이 제안을 시도하고 그것이 작동하지 않는 세트 –

답변

0

업데이트 : 코드 이 조각이 읽어, 파일을 열 키는 행 번호이고, 값이 공간에 의해 분리 된 단어의 집합 인 사전을 만들 것이다.

with open(fpath, 'r') as readf_obj: 
    line_words = {line_num+1: set(line.split()) for line_num, line in enumerate(readf_obj)} 
print(line_words) 

이게 당신이 원하는 무엇입니까? 원래


:
당신은 먼저 튜플로 변환 set(a_dict.values())하지 않아도 할 수 있습니다.

당신의 질문은 당신이하고 싶은 것을 분명히하지 않고, 을 올리는 것입니다. 어떤 부분에 초점을 맞출 지에 대한 의견이나 단서가없는 코드도 도움이되지 않습니다.

+0

인 것으로 사전을 계속 사용하려면. 또한 당신은 세트 코드 조각으로 내 질문에 대답 할 수 있었기 때문에 내가 원했던 것을 아는 것 같습니다. print_list2 D = –

+0

파일 세트 "", 라인 (109), (this_dic.values ​​()) 오류 : unhashable 유형 '에서' –

+0

파일 " ", 라인 (109), print_list2 세트 (this_dic.values ​​()) 형식 오류 : unhashable 유형 : 'a_dict = {1 : 'A', 2 '목록'이상한 –