2014-03-05 28 views
0

我有一個文本文件,a.txt中,具有:蟒蛇2.7之前列表中選擇的話編號

Hydrocortisone 10 MG/ML Topical Cream 
Tretinoin 0.25 MG/ML Topical Cream 
Benzoyl Peroxide 50 MG/ML Topical Lotion 
Ketoconazole 20 MG/ML Medicated Shampoo 
etc 

我需要一種方法來之前的第一號選擇任何詞,並將它們寫入另一個文件,b.txt:

Hydrocortisone 
Tretinoin 
Benzoyl Peroxide 
Ketoconazole 
etc 

我已經怎麼辦查找和文件替換一個基本的想法,但蟒蛇,它幾乎是可笑的,這種有限的把握,所以我最初的想法是做一些事情像

infile = open('a.txt') 
outfile = open('b.txt', 'w') 
replacements = {'1':'', '2':'' up to twenty and then a list based on words commonly occuring after the numbers such as 'topical':'' etc} 
for line in infile: 
for src, target in replacements.iteritems(): 
line = line.replace(src, target) 
outfile.write(line) 
infile.close() 
outfile.close() 

但是,只要刪除「替換」中指定的內容即可。有成千上萬的變化,所以我不能全部列出。

對不起,你爲什麼不去做一個循環,並使用isdigit()確定的第一個數字不是更清晰,並感謝所有幫助

+3

你到目前爲止嘗試了什麼? –

+1

對不起,但這不是StackOverflow的工作原理。您必須在研究,發佈您嘗試過的代碼,解釋其不起作用的原因以及詢問具體問題等方面付出努力。 – Christian

+0

正則表達式可以做到這一點,但它可能是一個先進的這種具體情況 –

回答

0

試試這個,這將分裂的數量,並且讓你的名字部分:

import re 

exp = re.compile(r'(\d+\.?\d+)') 

with open('mainfile.txt') as f, open('names.txt','w') as out: 
    for line in f: 
     line = line.strip() 
     if len(line): 
      try: 
       out.write('{}\n'.format(re.split(exp, line)[0].strip())) 
      except: 
       print('Could not parse {}'.format(line)) 

正則表達式\d+\.?\d+表示:

  • \d+一個或多個數字
  • \.?可選.(在正則表達式中註釋.具有特殊的意義,所以我們逃避它,當我們指的是字面.
  • \d+後面跟着一個或多個數字

()它圍繞它使一個捕獲組;其結果如下:

>>> x = r'(\d+\.?\d+)' 
>>> l = 'Benzoyl Peroxide 50 MG/ML Topical Lotion' 
>>> re.split(x, l) 
['Benzoyl Peroxide ', '50', ' MG/ML Topical Lotion'] 
+0

輝煌,完美的作品。非常感謝你,感謝你解釋它,這真的幫助我學習。 – lobe

0

?喜歡的東西:

writef = open('b.txt', 'w') 
with open('a.txt') as f: 
    while True: 
     line = f.readline() 
     if not line: 
      break 
     words = line.split() 
     for i in range(len(words)): 
      if words[i].replace('.', '').isdigit(): 
       writef.write(words[i-1] + '\n') 
       continue 
writef.close() 
+0

嗨,對不起,我一定要做的事情密集,因爲我得到SyntaxError:'break'外部循環。對不起,謝謝你的幫助 – lobe

+0

@lobe哦,這是我的錯,雖然忘了添加'while':) – Xufeng