如何解决如何删除文本的前10个字?
我有一个txt文件,其中包含GibránHalilGibrán的一首诗,从那里我必须删除前10个单词,可能还要加上一个地图并删除,但是我不能将其放在一起。我尝试了pop()。但是我不知道该怎么办。
for word in prophet:
if word is [0]:
prophet.pop[0]
if word is [1]:
prophet.pop[1]
print(prophet)
解决方法
在此处查找示例:
>>> text = "I have a txt file with a poem by Gibrán Halil Gibrán,from where I have to delete the first 10 words,probably with a map and delete,but I can't put it together. I tried this with pop (). But i don't have idea about how can i doit."
>>> text = ' '.join(text.split()[10:])
>>> text
"Halil Gibrán,but I can't put it together. I tried this with pop (). But i don't have idea about how can i doit."
,
您可以简单地使用split
方法:
s = "a bc d ef gh i jk l m p q r s"
ans = s.split(" ",10)[1]
print(ans) #gives "q r s"
,
调用以下函数删除前10个字:
def remove_words(text):
words = text.split()
return " ".join(words[10:])
因此,例如,整个脚本可能如下所示:
with open("file.txt") as f:
text = f.read()
text = remove_words(text)
with open("new_file.txt","w") as f:
f.write(text)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。