원본 파일을 다시 만들려면 파일을 단어 목록과 위치 목록으로 압축해야합니다. 내 프로그램은 또한 압축 된 파일을 가져 와서 원본 파일의 구두점과 대소 문자를 포함한 전체 텍스트를 다시 만들 수 있어야합니다. 내 프로그램은 목록이기 때문에 '['때문에 내 위치 목록을 수레로 변환 할 수 없습니다.
내 코드는 다음과 같습니다.
text = open("speech.txt")
CharactersUnique = []
ListOfPositions = []
DownLine = False
while True:
line = text.readline()
if not line:
break
TwoList = line.split()
for word in TwoList:
if word not in CharactersUnique:
CharactersUnique.append(word)
ListOfPositions.append(CharactersUnique.index(word))
if not DownLine:
CharactersUnique.append("\n")
DownLine = True
ListOfPositions.append(CharactersUnique.index("\n"))
w = open("List_WordsPos.txt", "w")
for c in CharactersUnique:
w.write(c)
w.close()
x = open("List_WordsPos.txt", "a")
x.write(str(ListOfPositions))
x.close()
with open("List_WordsPos.txt", "r") as f:
NewWordsUnique = f.readline()
f.close()
h = open("List_WordsPos.txt", "r")
lines = h.readlines()
NewListOfPositions = lines[1]
NewListOfPositions = map(float, NewListOfPositions)
print("Recreated Text:\n")
recreation = " " .join(NewWordsUnique[pos] for pos in (NewListOfPositions))
print(recreation)
내가 얻는 오류는 다음과 같습니다.
Task 3 Code.py", line 42, in <genexpr>
recreation = " " .join(NewWordsUnique[pos] for pos in (NewListOfPositions))
ValueError: could not convert string to float: '['
Python IDLE 3.5 (32 비트)를 사용하고 있습니다. 누구든지 이것을 고치는 방법에 대한 아이디어가 있습니까?
의 위치 값 list
을 list
인덱스이고 정수 여야하는 부동 소수점 으로 바꾸려는 이유는 무엇 입니까? 나는 이것이 XY 문제 라고 불리는 것의 예라고 생각했다 .
또한 PEP 8-Style Guide for Python Code를 따르지 않았기 때문에 코드를 이해하기 어렵다는 것을 알았습니다 . 특히, CamelCased
가이드 라인에 따라 클래스 이름을 위해 예약해야하는 변수 이름의 수 (모두는 아니지만) 가 있습니다.
또한 일부 변수에는 CharactersUnique
실제로 [대부분] 고유 한 단어가 포함 된와 같이 잘못된 이름이 있습니다.
그래서 제가했던 첫 번째 작업 중 하나는 모든 CamelCased
변수를 소문자와 같이 소문자 밑줄로 구분 된 단어로 변환하는 것 camel_case
입니다. 몇몇 경우에 나는 또한 그들의 실제 내용이나 역할을 반영하기 위해 그들에게 더 나은 이름을 주었다. 예를 들어 : CharactersUnique
가 unique_words
.
다음 단계는 with
블록의 끝에서 모든 파일이 자동으로 닫히도록 Python의 명령문을 사용하여 파일 처리를 개선하는 것이 었습니다 . 다른 경우에는 여러 파일 open()
호출을 하나로 통합했습니다 .
결국 거의 효과가 있었지만 그 때 개행 "\n"
문자를 입력 텍스트 파일의 개별 단어로 처리하는 접근 방식에 문제가 있음을 발견했습니다 . 이로 인해 파일이 다음 표현식에 의해 다시 생성 될 때 문제가 발생했습니다.
" ".join(NewWordsUnique[pos] for pos in (NewListOfPositions))
"\n"
원래 파일에없는 모든 문자가 발견 되기 전후에 하나의 공백을 추가하기 때문 입니다. 이 문제를 해결하기 for
위해 목록 이해력을 사용하는 대신 파일을 다시 생성 하는 루프를 작성했습니다. 그렇게하면 개행 "단어"를 올바르게 처리 할 수 있기 때문입니다.
어쨌든 다음은 재 작성된 (그리고 작동하는) 코드입니다.
input_filename = "speech.txt"
compressed_filename = "List_WordsPos.txt"
# Two lists to represent contents of input file.
unique_words = ["\n"] # preload with newline "word"
word_positions = []
with open(input_filename, "r") as input_file:
for line in input_file:
for word in line.split():
if word not in unique_words:
unique_words.append(word)
word_positions.append(unique_words.index(word))
word_positions.append(unique_words.index("\n")) # add newline at end of each line
# Write representations of the two data-structures to compressed file.
with open(compressed_filename, "w") as compr_file:
words_repr = " ".join(repr(word) for word in unique_words)
compr_file.write(words_repr + "\n")
positions_repr = " ".join(repr(posn) for posn in word_positions)
compr_file.write(positions_repr + "\n")
def strip_quotes(word):
"""Strip the first and last characters from the string (assumed to be quotes)."""
tmp = word[1:-1]
return tmp if tmp != "\\n" else "\n" # newline "words" are special case
# Recreate input file from data in compressed file.
with open(compressed_filename, "r") as compr_file:
line = compr_file.readline()
new_unique_words = list(map(strip_quotes, line.split()))
line = compr_file.readline()
new_word_positions = map(int, line.split()) # using int, not float here
words = []
lines = []
for posn in new_word_positions:
word = new_unique_words[posn]
if word != "\n":
words.append(word)
else:
lines.append(" ".join(words))
words = []
print("Recreated Text:\n")
recreation = "\n".join(lines)
print(recreation)
speech.txt
질문의 첫 번째 단락에서 자체 테스트 파일을 만들고 다음 결과로 스크립트를 실행했습니다.
Recreated Text:
I have to compress a file into a list of words and list of positions to recreate
the original file. My program should also be able to take a compressed file and
recreate the full text, including punctuation and capitalization, of the
original file. I have everything correct apart from the recreation, using the
map function my program can't convert my list of positions into floats because
of the '[' as it is a list.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다