2016-10-15 7 views
1

텍스트 구성에 도움이 필요합니다. CSV에 수천 개의 보코더 목록이 있습니다. 단어마다 용어, 정의 및 샘플 문장이 있습니다. 용어와 정의는 탭으로 구분되며 샘플 문장은 빈 줄로 구분됩니다.공백 라인을 무시하고 다른 모든 줄의 시작과 끝에 인용 부호 추가

샘플 문장을 큰 따옴표로 묶여 있도록 내가이를 구성 할
exacerbate worsen 

This attack will exacerbate the already tense relations between the two communities 

exasperate irritate, vex 

he often exasperates his mother with pranks 

execrable very bad, abominable, utterly detestable 

an execrable performance 

은, 이전과 자체 이후에는 빈 줄이 없으며, 문장의 용어는 하이픈으로 대체됩니다 : 예를 들어

. 기간이 끝난 후에 탭을 유지하면서 변경되는 모든 내용, 각 용어의 시작 부분에 새 줄이 표시되며 정의와 예제 문장 사이에 공백 만 있습니다. 플래시 카드 웹 응용 프로그램으로 가져 오기 위해이 형식이 필요합니다. 예를 들어 위의 사용

원하는 결과 : 나는 맥을 사용하고

exacerbate worsen "This attack will – the already tense relations between the two communities" 
exasperate irritate, vex "he often – his mother with pranks" 
execrable very bad, abominable, utterly detestable "an – performance" 

. 기본 명령 행 (정규식 포함)과 파이썬을 알고 있지만,이 점을 직접 이해할 수는 없습니다. 너가 나를 도울 수 있으면, 나는 매우 감사한다.

+0

정의와 예제 사이에만 공백이 필요합니까? 아니면 거기에 탭이 있어야합니까? – rubik

+0

정의와 예제 문장 사이의 공백 만 사용하십시오. 설명을 요청 해 주셔서 감사합니다. 내 질문을 업데이트 할게. – Vincent

+0

원본 CSV 형식을 표시 할 수 있습니까 –

답변

1

엽니 다 입력 파일이있는 디렉토리에 터미널. .py 파일에 다음 코드를 저장 :

import sys 
import string 
import difflib 
import itertools 


with open(sys.argv[1]) as fobj: 
    lines = fobj.read().split('\n\n') 

with open(sys.argv[2], 'w') as out: 
    for i in range(0, len(lines), 2): 
     line1, example = lines[i:i + 2] 
     words = [w.strip(string.punctuation).lower() 
       for w in example.split()] 

     # if the target word is not in the example sentence, 
     # we will find the most similar one 
     target = line1.split('\t')[0] 
     if target in words: 
      most_similar = target 
     else: 
      most_similar = difflib.get_close_matches(target, words, 1)[0] 
     new_example = example.replace(most_similar, '-') 
     out.write('{} "{}"\n'.format(line1.strip(), new_example.strip())) 

이 프로그램은 입력 파일 이름과 명령 행 인수로 출력 파일 이름이 필요합니다.

program.py 위의 프로그램입니다
$ python program.py input.txt output.txt 

, input.txt 당신의 입력 파일이며, output.txt는 당신이 필요로하는 형식으로 작성 될 파일입니다 : 즉, 터미널에서 다음 명령을 실행합니다.


제공 한 예와 비교하여 프로그램을 실행했습니다. 질문에 공백 만 있기 때문에 수동으로 탭을 추가했습니다. 단어 exacerbate 있더라도

exacerbate worsen "This attack will - the already tense relations between the two communities" 
exasperate irritate, vex "he often - his mother with pranks" 
execrable very bad, abominable, utterly detestable "an - performance" 

프로그램이 제대로 대입 exacerbates 번째 예에서 대시이 프로그램에 의해 생성 된 출력된다. 파일을 사용하지 않고도이 기술이 파일의 모든 단어에 대해 작동한다는 것을 보장 할 수는 없습니다.

+0

굉장! 귀하의 프로그램이 아름답게 실행되었고 번거롭지 않게 flashcards 웹 응용 프로그램으로 결과를 가져올 수있었습니다. 당신 덕분에 나는 음성을 외우는데 더 많은 시간을 할애 할 수 있습니다 :) – Vincent

+0

@ Vincent 내가 도울 수있어서 기쁩니다! 변형이 올바르지 않은 경우 프로그램을 수정할 수 있도록 의견을 남겨주십시오. 예를 들어, 불규칙 동사가 올바르게 대체되지 않았습니다. – rubik

0

반드시 그렇지는 방탄하지만 예에 따라 일을 할 것입니다 스크립트 :

import sys 
import re 
input_file = sys.argv[1] 


is_definition = True 

current_entry = "" 
current_definition = "" 

for line in open(input_file, 'r'): 
    line = line.strip() 

    if line != "": 
     if is_definition == True: 
      is_definition = False 

      [current_entry, current_definition] = line.split("\t") 

     else: 
      is_definition = True 

      example = line 

      print (current_entry + "\t" + current_definition + ' "' + re.sub(current_entry + r'\w*', "-", line) + '"') 

출력 :

exacerbate worsen "This attack will - the already tense relations between the two communities" 
exasperate irritate, vex "he often - his mother with pranks" 
execrable very bad, abominable, utterly detestable "an - performance" 

우리의 현재 접근 방식의 문제인지는하지 않습니다 "go-went"또는 "bring-bring"또는 "seek-sought"와 같은 불규칙 동사에서 작동합니다.

+0

두 번째 예제에서는 작동하지 않습니다. – rubik

+0

그러나 게시물 예제와 동일한 결과를 얻었습니다. – dgg32

+0

아니요, 두 번째 것을 확인하십시오. – rubik

0

시도 :

suffixList = ["s", "ed", "es", "ing"] #et cetera 
file = vocab.read() 
file.split("\n") 

vocab_words = [file[i] for i in range(0, len(file)-2, 4)] 
vocab_defs = [file[i] for i in range(2, len(file), 4)] 

for defCount in range(len(vocab_defs)): 
    vocab_defs[defCount] = "\"" + vocab_defs[defCount] + "\"" 

newFileText = "" 
for count in range(len(vocab_words)): 
    vocab_defs[count] = vocab_defs[count].replace(vocab_words[count].split(" ")[0], "-") 
    for i in suffixList: 
     vocab_defs[count] = vocab_defs[count].replace("-%s" % i, "-") 
    newFileText += vocab_words[count] 
    newFileText += " " 
    newFileText += vocab_defs[count] 
    newFileText += "\n" 

new_vocab_file.write(newFileText) 

출력 :

============== RESTART: /Users/chervjay/Documents/thingy.py ============== 
exacerbate worsen "This attack will - the already tense relations between the two communities" 
exasperate irritate, vex "he often - his mother with pranks" 
execrable very bad, abominable, utterly detestable "an - performance" 

>>> 
+0

예에서 단어를 대시로 바꿔야합니다. – rubik

+0

주의 해 주셔서 감사합니다! – rassar

+0

하지만 지금은 @ dgg32의 대답과 같은 문제가 있습니다. – rubik

0
#!/usr/local/bin/python3 

import re 

with open('yourFile.csv', 'r') as myfile: 
    data = myfile.read()  

print(re.sub(r'(^[A-Za-z]+)\t(.+)\n\n(.+)\1[s|ed|es|ing]*(.+)$',r'\1\t\2 "\3-\4"', data, flags = re.MULTILINE)) 

출력 :

악화 악화 "이 공격은 것 - 두 공동체 사이에 이미 긴장 관계"

화나게의 자극은, "그는 종종 - 장난과 그의 어머니"짜증나게

매우 경멸할만한, 가증스러운, 완전히 혐오스러운 "성능"