2017-10-16 2 views
0

마이리스트 종료 :파이썬 : 목록에 n을 r에 의 t을 대체하는 시작 n n을 제외하고 n을의 r n 의 t으로

['\n\r\n\tThis article is about sweet bananas. For the genus to which banana plants belong, see Musa (genus).\n\r\n\tFor starchier bananas used in cooking, see Cooking banana. For other uses, see Banana (disambiguation)\n\r\n\tMusa species are native to tropical Indomalaya and Australia, and are likely to have been first domesticated in Papua New Guinea.\n\r\n\tThey are grown in 135 countries.\n\n\n\r\n\tWorldwide, there is no sharp distinction between "bananas" and "plantains".\n\nDescription\n\r\n\tThe banana plant is the largest herbaceous flowering plant.\n\r\n\tAll the above-ground parts of a banana plant grow from a structure usually called a "corm".\n\nEtymology\n\r\n\tThe word banana is thought to be of West African origin, possibly from the Wolof word banaana, and passed into English via Spanish or Portuguese.\n']

예 코드 :

import requests 
from bs4 import BeautifulSoup 
import re 
re=requests.get('http://www.abcde.com/banana') 
soup=BeautifulSoup(re.text.encode('utf-8'), "html.parser") 
title_tag = soup.select_one('.page_article_title') 
print(title_tag.text) 
list=[] 
for tag in soup.select('.page_article_content'): 
    list.append(tag.text) 
#list=([c.replace('\n', '') for c in list]) 
#list=([c.replace('\r', '') for c in list]) 
#list=([c.replace('\t', '') for c in list]) 
print(list) 

웹 페이지를 긁어 낸 후에 데이터 정리를해야합니다. "\r", "\n", "\t"을 모두 ""으로 바꾸고 싶지만이 경우 자막이 있습니다. 자막과 문장이 혼합되어 있습니다 ().

모든 자막은 항상 \n\n으로 시작하고 \n\r\n\t으로 끝납니다. \aEtymology\a과 같이이 목록에서 구분할 수있는 작업이 가능할 수 있습니다. \n\n\n\r\n\t\a으로 따로 대체하는 경우 다른 부분의 요소가 \n\n\r 일 때 첫 번째 원인은 \a\r이됩니다. 미리 감사드립니다!

답변

1

접근하면

  1. 교체리스트
  2. 에서 지정 문자열 <subtitles>\n, \r이 목록
  3. \t 등이 실제 자막
  4. 로 정의 스트링을 교체 자막 바꾸기

코드

l=['\n\r\n\tThis article is about sweet bananas. For the genus to which banana plants belong, see Musa (genus).\n\r\n\tFor starchier bananas used in cooking, see Cooking banana. For other uses, see Banana (disambiguation)\n\r\n\tMusa species are native to tropical Indomalaya and Australia, and are likely to have been first domesticated in Papua New Guinea.\n\r\n\tThey are grown in 135 countries.\n\n\n\r\n\tWorldwide, there is no sharp distinction between "bananas" and "plantains".\n\nDescription\n\r\n\tThe banana plant is the largest herbaceous flowering plant.\n\r\n\tAll the above-ground parts of a banana plant grow from a structure usually called a "corm".\n\nEtymology\n\r\n\tThe word banana is thought to be of West African origin, possibly from the Wolof word banaana, and passed into English via Spanish or Portuguese.\n'] 

import re 
regex=re.findall("\n\n.*.\n\r\n\t",l[0]) 
print(regex) 

for x in regex: 
    l = [r.replace(x,"<subtitles>") for r in l] 

rep = ['\n','\t','\r'] 
for y in rep: 
    l = [r.replace(y, '') for r in l] 

for x in regex: 
    l = [r.replace('<subtitles>', x, 1) for r in l] 
print(l) 

출력

['\n\nDescription\n\r\n\t', '\n\nEtymology\n\r\n\t'] 

['This article is about sweet bananas. For the genus to which banana plants belong, see Musa (genus).For starchier bananas used in cooking, see Cooking banana. For other uses, see Banana (disambiguation)Musa species are native to tropical Indomalaya and Australia, and are likely to have been first domesticated in Papua New Guinea.They are grown in 135 countries.Worldwide, there is no sharp distinction between "bananas" and "plantains".\n\nDescription\n\r\n\tThe banana plant is the largest herbaceous flowering plant.All the above-ground parts of a banana plant grow from a structure usually called a "corm".\n\nEtymology\n\r\n\tThe word banana is thought to be of West African origin, possibly from the Wolof word banaana, and passed into English via Spanish or Portuguese.'] 
+0

이것은 아주 청초합니다! 그리고 쉽게 배우고 이해할 수 있습니다. 그냥 질문 목록 = [목록에 r에 대한 r.replace ('', x, 1)], 1은 무엇을 사용합니까? 내가 그것을 제거했을 때, 그것은 같은 결과를 출력했다.그냥 호기심 :) 감사합니다! – Makiyo

+0

@Makiyo 1은 의 첫 번째 발생만을 대체합니다. 1을 제거하면 자막이 출력물에서 동일하게됩니다. –

0
import re  

print([re.sub(r'[\n\r\t]', '', c) for c in list]) 

나는 당신이 정규식

+0

나는 이것이 그의 "\ n 개의 \ 연구 \ (t)가"말은 정답이라고 생각하지 않는다 '\ n'을하거나, 당신이 '\ r에'또는 '\의 t' "\ n \ r \ t"으로 읽으면 다음 문장은 "시작 \ n \ n이고 \ n \ r \ n \ t ....."으로 끝납니다. 그의 예를 확인하십시오, 전혀 "\ n \ r \ t"이 없습니다 –

0

당신은 정규 표현식을 사용하여이 작업을 수행 할 수 있습니다 사용할 수 있습니다 생각 :

import re 
subtitle = re.compile(r'\n\n(\w+)\n\r\n\t') 
new_list = [subtitle.sub(r"\a\g<1>\a", l) for l in li] 

\g<1>는 첫 번째 정규 표현식에서 (\ + w)에 대한 역 참조입니다. 그곳에있는 것을 재사용 할 수 있습니다.

+0

안녕하세요! 나는 그것을 시도했지만 그것이 작동하지 않는, 그것은 내가 잘못된 장소에 넣었는지 모르겠다. 방금 위의 코드 전체를 업로드했습니다. – Makiyo

+0

작동하지 않는 이유는 무엇입니까? 오류가 있습니까? –

+0

AttributeError : 'Response'객체에 'compile'속성이 없습니다. – Makiyo