python 作业求助

巫妖天下 2014-10-02 01:05:08
Write a function called preprocess_line that takes a line of text (string) as an argument.
It should return a new string which removes all characters from the line that are not in
the following set: characters in the English alphabet, space, comma, or period. (That
is, remove characters with accents and umlauts and the other punctuation marks). Your
function should also lowercase all remaining characters and convert all numerals to `0'.

写一个名为preprocess_line函数,将一个行文本(字符串)作为参数。
它返回值应该该是一个新的字符串,将不在以下内容中的字符统统删除:英文字母,空格,逗号或句号字符。 (这就是,删除带有口音和变音符号和其他标点符号的字符)。你的函数也应该将所有剩余的字符变成小写和将剩下的所有的数字转换为0。

...全文
208 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
lsjfdjoijvtghu 2014-10-03
  • 打赏
  • 举报
回复
#!/usr/bin/python
# -*- coding: utf-8 -*-
我会这么写
#!/usr/bin/env python
#-*- coding=utf-8 -*-
A_G_Lamperouge 2014-10-02
  • 打赏
  • 举报
回复
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
s = '!@#4A5^&*9&^4DFGhj<论坛>\'ds\\regex\"\'__>Z...*^8,-0-=._'

#用正则表达式
def reprocess_line(sText):
	template1 = re.compile('[^a-zA-Z0-9\.,]')
	template2 = re.compile('\d')
	sText = re.sub(template1, '',sText)
	sText = re.sub(template2, '0', sText)
	return sText.lower()

#最直观的
def reprocess_line1(sText):
	#如果默认是utf-8
	sText = unicode(sText,'utf-8')
	newText = ''
	for i in sText:
		#过滤
		if (ord(i) >= 65 and ord(i) < (65^26)):
			newText += i
		if (ord(i) >= 97 and ord(i) < (97^26)):
			newText += i
		if (ord(i) >= 48 and ord(i) < (48^10)):
			newText += '0'
		if (i=='.' or i==','):
			newText += i
	return newText.lower()
	
print reprocess_line(s)
print reprocess_line1(s)

37,718

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧