2015-08-29 17 views

回答

1
re.sub(r"[ao]$","",word) 

這應該爲你做。

0

首先讀取文件並拆分行。之後,切斷了最後一個字符,如果你的條件滿足並追加新的字符串列表,包含分析和修改字符串/線:

#!/usr/bin/env python3 
# coding: utf-8 

# open file, read lines and store them in a list 
with open('words.txt') as f: 
    lines = f.read().splitlines() 

# analyse lines read from file 
new_lines = [] 
for s in lines: 
    # analyse last char of string, 
    # get rid of it if condition is fulfilled and append string to new list 
    s = s[:-1] if s[-1] in ['a', 'o'] else s 
    new_lines.append(s) 

print(new_lines) 
1

試試這個:

import re 
import os 

# Read the file, split the contents into a list of lines, 
# removing line separators 
with open('input.txt') as infile: 
    lines = infile.read().splitlines() 

# Remove any whitespace around the word. 
# If you are certain the list doesn't contain whitespace 
# around the word, you can leave this out... 
# (this is called a "list comprehansion", by the way) 
lines = [line.strip() for line in lines] 

# Remove letters if necessary, using regular expressions. 
outlines = [re.sub('[ao]$', '', line) for line in lines] 

# Join the output with appropriate line separators 
outdata = os.linesep.join(outlines) 

# Write the output to a file 
with open('output.txt', 'w') as outfile: 
     outfile.write(outdata) 
+0

這非常有幫助!謝謝:D – osztenkurden

+0

當你去掉文本時,表達式應該是'line.strip()'而不是'lines.strip()' –

+0

@FernandoMatsumoto更正,謝謝。 –

相關問題