我有文字的列表的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