我有文字的列表的txt文件,這樣的事情:如果刪除單詞中的最後一個字母,如果它是'a'或'o'?
adsorbowanie
adsorpcje
adular
adwena
adwent
adwentnio
adwentysta
adwentystka
adwersarz
adwokacjo
我想刪除每一個字的最後一個字母,如果字母是「A」或「O」。
我對此很新,所以請簡單說明一下。
我有文字的列表的txt文件,這樣的事情:如果刪除單詞中的最後一個字母,如果它是'a'或'o'?
adsorbowanie
adsorpcje
adular
adwena
adwent
adwentnio
adwentysta
adwentystka
adwersarz
adwokacjo
我想刪除每一個字的最後一個字母,如果字母是「A」或「O」。
我對此很新,所以請簡單說明一下。
re.sub(r"[ao]$","",word)
這應該爲你做。
首先讀取文件並拆分行。之後,切斷了最後一個字符,如果你的條件滿足並追加新的字符串列表,包含分析和修改字符串/線:
#!/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)
試試這個:
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)
這非常有幫助!謝謝:D – osztenkurden
當你去掉文本時,表達式應該是'line.strip()'而不是'lines.strip()' –
@FernandoMatsumoto更正,謝謝。 –
有一個的endsWith( )方法 – Moritz