[英]Python: Removing the numbers from a numbered list and removing items with certain characters
我有一个文本文件,其中包含药物和化学结构的编号列表。
有什么办法可以去掉物质名称前面的数字吗?
这是我到目前为止的代码:
new_file = open("string_cleaned.txt", "w")
for line in open("string.txt", "r"):
x = txt.lsplit(", ", 1)[1]
new_file.write(x)
new_file.close()
目标
From:
1 Substance 1
2 Substance 2
To:
Substance 1
Substance 2
不是防弹解决方案,但如果您的数据像您的示例,它可能会起作用。 如果它需要更多的调整告诉我。
import string
alphabet = string.ascii_lowercase + string.ascii_uppercase
YourFile = open("yourFile.txt", "r")
listOfLines = YourFile.readlines()
for lineIndex in range(len(listOfLines)):
for char in listOfLines[lineIndex]:
if char in alphabet:
editedLine = listOfLines[lineIndex].split(char,1)[1]
editedLine = str(lineIndex + 1) + " " + char + editedLine #(optional) If you need the Index numbers beside your items
listOfLines[lineIndex] = editedLine
break
anotherFile = open("anotherFile.txt", "w")
anotherFile.writelines(listOfLines)
anotherFile.close
所以在这里编辑之后是解决方案
YourFile = open("yourFile.txt", "r")
listOfLines = YourFile.readlines()
for index in range(len(listOfLines)):
listOfLines[index] = listOfLines[index].lstrip("0123456789")
listOfLines[index] = listOfLines[index].lstrip(" ")
print(listOfLines[index])
anotherFile = open("anotherFile.txt", "w")
anotherFile.writelines(listOfLines)
anotherFile.close
编辑:一个特定的解决方案。
import re
result = ""
for line in open("string.txt"):
result += re.sub(r"(?<=\s)[^a-zA-Z]*", "", line)
with open("string_cleaned.txt", "w") as file:
file.write(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.