刮取时删除标题中的某些文本

2024-09-30 20:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正试图在youtube上搜索播放列表。 废品工程,但我想得到的只是标题的一部分

例如:

  • 视频标题为:

    'Et si on mangeait la connaissance? | Idriss Aberkane | TEDxPanthéonSorbonne'

  • 通过刮擦我只想得到:

    'Et si on mangeait la connaissance?'

我想删除|之后的所有字符

有可能吗


Tags: 标题视频youtubeon工程播放列表laet
3条回答
import re

p = re.compile("(.*?) \|.*")
m = p.search('Et si on mangeait la connaissance? | Idriss Aberkane | TEDxPanthéonSorbonne')

这将提供所需的字符串:

m[1]

如果你确定每个标题中都有“|”字符,你可以这样写

string title = "test title | about anything";
string result ="";
if(title.indexOf("|") > -1)
    result = title.substring(0, test.indexOf("|"));

如果要在第一次出现“|”时删除所有内容,可以编写以下代码:

scrap_result = 'Et si on mangeait la connaissance? | Idriss Aberkane | TEDxPanthéonSorbonne' # this is the scrap result of the title you get you can user str() to be precise so you only get string is a title.
scrap_result = scrap_result[:scrap_result.find("|")] # this will give you result before the first occurrence of '|' but it includes trailing space at the end if you want to remove it use scrap_result.strip() 

相关问题 更多 >