2012-04-02 2 views
1

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
이상으로 바꿔야합니다. 출력은 다음과 같이 문자열 발생 횟수로 표시되어야합니다. $ 0 또는 $ 136 "Currency123 '와'TOM '(일반적으로 대체해야

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 
+3

PEP8 (http://www.python.org/dev/peps/pep-0008/), 아니요 의도 된 범죄. – Benjamin

+0

당신은 정규 표현식에 대해 알고 있습니다. – Marcin

+0

필요한 경우 각 패턴의 발생 횟수를 계산하는 것만으로 파일의 텍스트를 바꿀 필요가 없습니다. 그냥're.findall()'을 사용하십시오. –

답변

1

통화가 즉, 나는 내가 이것에 대해 알려 주시기 바랍니다 현재로서는이 방법이

DATE123=2 smileys123=2 Currency123=6 AGENT123=5 

표시 나이 국세청 따옴표 이름) AGENT123으로 대체되어야한다 더 많은

나는 경우에 당신이 할 수있는, 수업 Repalce는 사전으로 대체해야한다고 생각 이상 (이 방법을 함께 제공하기 때문에) 적은 코드를 작성합니다. 사전은 wtih를 대체해야하는 항목을 추적 할 수 있으며 교체 요구 사항을 동적으로 변경하기위한 더 많은 옵션을 제공합니다. 그러면 코드가 더 명확하고 이해하기 쉬울 것입니다. 대체 단어가 많을수록 짧습니다.

편집 : 대체 단어 목록을 텍스트 파일에 보관하고 사전에로드 할 수 있습니다. 대체 단어를 수업에 하드 코딩하는 대신 그건 내가 생각하기에 좋은 생각이야. 당신이 더 많은 말했다 않았기 때문에, 그때는 너무 적은 코드를 작성해야 할 더 이해 (그리고 청소기!)

남기려면 ... 코드의 스타일이 아닌

# Here is a comment 

를 사용 가장 좋은 방법은보다 나은 코딩 스타일을 배우고 싶다면 http://www.python.org/dev/peps/pep-0008/#pet-peeves 또는 심지어 전체 장을 읽으십시오.

통화인지, 'Tom'인지, 날짜인지 확인하는 정규식입니다.

import re 

while True: 
    myString = input('Enter your string: ') 

    isMoney = re.match('^\$[0-9]+(,[0-9]{3})*(\.[0-9]{2})?$', myString) 
    isName = re.match('^\'+\w+\'$', myString) 
    isDate = re.match('^[0-1][0-9]\/[0-3][0-9]\/[0-1][0-9]{3}$', myString) 
    # or try '^[0-1]*?\/[0-9]*\/[0-9]*$ If you want 0/0/0 too... 

    if isMoney: 
     print('It is Money:', myString) 
    elif isName: 
     print('It is a Name:', myString) 
    elif isDate: 
     print('It is a Date:', myString) 
    else: 
     print('Not good.') 

Sanple 출력 :

Enter your string: $100 
It is Money: $100 
Enter your string: 100 
Not good. 
Enter your string: 'Tom' 
It is a Name: 'Tom' 
Enter your string: Tom 
Not good. 
Enter your string: 01/15/1989 
It is a Date: 01/15/1989 
Enter your string: 01151989 
Not good. 

당신이 isSomething 변수 중 하나 조건을 대체 할 수는 정확히 할 필요가 무엇인지에 따라 달라집니다. 나는 이것이 도움이되기를 바랍니다. 정규 표현식에 대해 자세히 알고 싶다면 "Regular Expression Primer" 또는 Python's RE Page을 확인하십시오.

+0

서두를 때 코멘트가 바뀌 었습니다. :) – Rajeev

+0

'boolean' 변수로 수정되었는데, 이것이 코드에 더 잘 맞을 수도 있습니다. – George

+0

감사합니다. 사용하는 최선의 방법을 찾으려고합니다. – Rajeev

1

필요한 모든 대체품을 제공하는 것은 아닙니다. 그러나 여기에는 정규 표현식과 기본 사전을 사용하여 데이터의 요소를 계산하는 방법이 있습니다. 문자열 바꾸기가 실제로 필요한 경우 다음을 이해할 수 있습니다.

lines = [ 
    "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", 
    "ID674 2gb Hi there! Welcome to Optus Web Chat 0/0/0 . $5.45 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'" 
] 

import re 
from collections import defaultdict 

p_smiley = re.compile(r':\)|:-\)') 
p_currency = re.compile(r'\$[\d.]+') 
p_date = re.compile(r'(\d{1,4}[/-]\d{1,4}[/-]\d{1,4})') 

count_dict = defaultdict(int) 

def count_data(type, count): 
    global count_dict 
    count_dict[type] += count 

for line in lines: 
    count_data('smiley', len(re.findall(p_smiley, line))) 
    count_data('date', len(re.findall(p_date, line))) 
    count_data('currency', len(re.findall(p_currency, line))) 
+0

매우 감사합니다. – Rajeev

관련 문제