Chat.txt文/字的文件从计数蟒蛇
ID674 25/01/1986 Thank you for choosing Optimus prime. Please wait for an Optimus prime Representative to respond. You are currently number 0 in the queue. You should be connected to an agent in approximately 0 minutes.. You are now chatting with 'Tom' 0 <br/>
ID674 2gb Hi there! Welcome to Optus Web Chat 0/0/0 . How can I help you today? 1
ID674 25-01-1986 I would like to change my bill plan from $0 with 0 expiry to something else $136. I find it very unuseful. Sam my phone no is 9838383821 2
在上述文字只是在file.My需要几行的例子是,所有的日期,例如25/01/1986或0/0/0应替换为“DATE123”。
然后:)应该换成“smileys123”。 货币即$ 0或$ 136应替换为“Currency123”
'TOM'(通常代理商名称在单引号中)应替换为AGENT123
等等。输出应该是字符串的出现次数显示
DATE123=2 smileys123=2 Currency123=6 AGENT123=5
我有这样的方法,因为现在请让我知道这一点,
class Replace:
dateformat=DATE123
smileys=smileys123
currency=currency123
count_dict={}
function count_data(type,count):
global count_dict
if type in count_dict:
count_dict[type]+=count
else:
count_dict = {type:count}
f=open("chat.txt")
while True:
for line in f.readlines():
print line,
if ":)" in line:
smileys = line.count(":)")
count_data("smileys",smileys)
elif "$number" in line : #how to see whether it is currency or nor??
currency=line.count("$number") //how can i do this
count_data("currecny",currency)
elif "1/2/3" in line : #how to validate date format
dateformat=line.count("dateformat") #how can i do this
count_data("currency",currency)
elif validate-agent-name in line:
agent_name=line.count("agentname") #How to do this get agentname in single quotes
count_data("agent_name",agent_name)
else:
break
f.close()
for keys in count_dict:
print keys,count_dict[keys]
The following would be the ouput
DATE123=2 smileys123=2 Currency123=6 AGENT123=5
你应该阅读PEP8(http://www.python.org/dev/peps/pep-0008/),否违法意图。 – Benjamin 2012-04-02 16:54:05
你知道正则表达式吧? – Marcin 2012-04-02 17:00:38
如果您只需要计算每个模式的出现次数,则不需要替换文件中的文本。只需使用're.findall()'。 – 2012-04-02 17:09:08