『壹』 python程序:輸入一個字元串,將其中字母'a'濾掉,生成另一個字元串
代碼:
print(''.join(c for c in input() if c!='a'))
運行結果截圖:
『貳』 python 爬蟲怎麼過濾正文以外的
利用bs4查找所有的div,用正則篩選出每個div裡面的中文,找到中文字數最多的div就是屬於正文的div了。定義一個抓取的頭部抓取網頁內容:
importrequests
headers={
'User-Agent':'Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/47.0.2526.106Safari/537.36',
'Host':'blog.csdn.net'}
session=requests.session()
defgetHtmlByRequests(url):
headers.update(
dict(Referer=url,Accept="*/*",Connection="keep-alive"))
htmlContent=session.get(url=url,headers=headers).content
returnhtmlContent.decode("utf-8","ignore")
統計文字的正則:
importre
#統計中文字數
defcountContent(string):
pattern=re.compile(u'[u1100-uFFFD]+?')
content=pattern.findall(string)
returncontent
查找每一個div,統計每一個div的文字,只保留文字最多的那個div:
#分析頁面信息
defanalyzeHtml(html):
#初始化網頁
soup=BeautifulSoup(html,"html.parser")
part=soup.select('div')
match=""
forparagraphinpart:
content=countContent(str(paragraph))
iflen(content)>len(match):
match=str(paragraph)
returnmatch
最後的調用幾個函數即可:
defmain():
url="http://blog.csdn.net/"
html=getHtmlByRequests(url)
mainContent=analyzeHtml(html)
soup=BeautifulSoup(mainContent,"html.parser")
print(soup.select('div')[0].text)
『叄』 python如何從文本中篩選出帶指定漢字的句子
#coding=gbk
#下面就是代碼,測試了一下沒有問題
#python 2.7.5
def srch(fileName):
f = open(fileName,'r').read()
s = f.split('\n')
a0 = s[0]
for i in range(0,len(s)):
if len(s) == 1: #這一行我不知道有沒有用,判斷文本是否只有一行
if a0[:1] != '#':
print '0' #return 0
break
a = s[i]
if a[:1] == '#':
print '-1' #return -1
else:
print '0' #return 0
print srch('abc.txt') #abc.txt is your file
『肆』 Python過濾關鍵詞怎麼做呢,在線等
你直接in就可以了
filter_words=['aaa','bbb','ccc']
test='afewfjlkkbbbsdfewfe'
forwinfilter_words:
ifwintest:
print"error"
break
如果解決了您的問題請採納!
如果未解內決請繼續容追問
『伍』 如何用python去掉文本中的\
s=r'123456'#r表示原生字元,即字元串中的不是用來轉義,而是其本身
print(s.replace('\',''))
運行結果:
123456