2014-10-14 4 views
-1

과제는 다음과 같습니다 : 문장을 읽는 Python 프로그램을 작성하십시오. 프로그램은 문자열 (사용자 입력)을 목록으로 변환하고 문장을 문자열 개체 목록으로 인쇄합니다. 그런 다음 프로그램에서 루프를 사용하여 목록에서 문장 부호 (구두점 목록에 나타나는)를 제거합니다. 마지막으로 프로그램은 목록을 문자열로 변환하고 구두점없이 문장을 인쇄합니다. 다음 구두점 목록을 프로그램에 복사해야합니다.목록에서 중복 요소를 제거하는 방법은 무엇입니까?

구두점 = [ '(', ')', '?', ':', ';', ',', '.', '!' , '/', '' '' ' "," "]

참고 : 문자열 목록을 변환 할 수는 STR 클래스의 방법을 결합 사용

을 그래서 기본적으로 모든있어. 내 출력을 보여줍니다

#punctuation list 
punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'", " "] 

#make an empty list for string to list 
converted_list = [] 
import copy 
#tell user to input a sentence 
sentence = str(input("Type in a line of text: ")) 

#Convert str to list 
for char in sentence: 
    converted_list.append(char) 
    newlist = copy.deepcopy(converted_list) 
    #remove punctuation from this list 
    for character in newlist: 
     if (character in punctuation): 
      newlist.remove(character) 
      newline = "".join(newlist) 


print(converted_list) 
print(newline) 

그러나 문제는 다음과 같습니다 :

다운이 내 코드입니다

첫 번째 "공백"문자 만 제거합니다. 'are'다음에 두 번째 'space'를 어떻게 제거 할 수 있습니까?

+0

당신의 들여 쓰기 맞 시도? 'newlist = ... '의 모든 것이 나에게 들여 쓰기되어 있지 않은 것처럼 보입니다. – Blckknght

+0

여전히 나에게 동일한 입력을 제공합니다 :/ – pythonnub

+0

정규식에 대한 re-python-library에 대해 들어 보셨습니까? 특히 re.replace() 메서드는 무엇입니까? –

답변

-3

문자열에서 공백을 제거하기 위해 nospace 키워드를 사용할 수 있습니다. 예 :

인 str1 = "TH ABC 123"

str1sp = nospace (srt1)

인쇄 (str1sp)

ANS :

THABC123

+0

파이썬에는'nospace '가 없습니다. – Matthias

0

시도 유지 가능하면 간단합니다 :

#punctuation list 
punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'", " "] 

#make an empty list for string to list 
converted_list = [] 
#tell user to input a sentence 
sentence = str(input("Type in a line of text: ")) 

#Convert str to list 
for char in sentence: 
    if char not in punctuation: 
     converted_list.append(char) 

print(converted_list) 
print("".join(converted_list)) 

출력은 다음과 같습니다

Type in a line of text: "Hey! Where are you?" 
['H', 'e', 'y', 'W', 'h', 'e', 'r', 'e', 'a', 'r', 'e', 'y', 'o', 'u'] 
HeyWhereareyou 
+0

omg 정말 고마워요! 예,이 방법은 훨씬 깔끔하고 읽기가 훨씬 쉬워 보입니다. – pythonnub

0

sentence = str(input("Type in a line of text: ") 
punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'", " "] 
converted_list = [char for char in sentence if char not in punctuation] 
print(converted_list) 
관련 문제