我有一个用Python打开的txt文件。我正在尝试删除符号并按字母顺序排列其余单词。删除句点,逗号等不是问题。但是,当我将破折号与其他符号一起添加到列表中时,似乎无法删除带有空格的破折号。
这是我打开的示例:
content = "The quick brown fox who was hungry jumps over the 7-year old lazy dog"
这就是我想要的(已删除句点,并且未附加到单词上的破折号):
content = "The quick brown fox who was hungry jumps over the 7year old lazy dog"
但是我要么得到了(所有破折号都删除了):
content = "The quick brown fox - who was hungry - jumps over the 7-year old lazy dog"
或者这个(未删除破折号):
f = open("article.txt","r")
# Create variable (Like this removing " - " works)
content = f.read()
content = content.replace(" - "," ")
# Create list
wordlist = content.split()
# Which symbols (If I remove the line "content = content.replace(" - "," ")",the " - " in this list doesn't get removed here)
chars = [",",".","'","(",")","‘","’"," - "]
# Remove symbols
words = []
for element in wordlist:
temp = ""
for ch in element:
if ch not in chars:
temp += ch
words.append(temp)
# Print words,sort alphabetically and do not print duplicates
for word in sorted(set(words)):
print(word)
这是我的全部代码。添加content.replace()即可。但这不是我想要的:
content = content.replace(" - "," ")
它像这样工作。但是,当我删除chars
时,content = "The quick brown fox who was hungry jumps over the 7year old lazy dog"
中的“空白+破折号+ whitspace”不会被删除。
如果我将其替换为“-”(没有空格),则会得到我不想要的内容:
chars
是否可以使用7-year
A
B
C
The
brown
dog
fox
hungry
jumps
lazy
old
over
quick
the
was
who
之类的列表执行此操作,还是我唯一选择使用.replace()进行此操作。
Python是否有一个特殊的原因为什么Python首先要按字母顺序对大写字母排序,然后对不大写的单词分别排序?
就像这样(只是添加了字母ABC以强调我要说的话):
{{1}}