今天给大家分享 -20个进阶必看的文本处理Python函数。
移除字符串两端的空白字符或指定字符。示例:
text = " hello, world! "cleaned_text = text.strip()print(cleaned_text)
分别用于去除左边和右边的指定字符。
根据指定的分隔符将字符串分割成列表。示例:
data = "apple, banana, cherry"fruits = data.split(", ")print(fruits)
替换字符串中的某部分文本。示例:
text = "i love programming in python"new_text = text.replace("python", "javascript")print(new_text)
将列表中的元素连接成一个字符串。示例:
words = ("hello", "world")sentence = " ".join(words)print(sentence)
查找子字符串的位置,只返回第一次出现的位置。示例:
text = "python is fun!"position = text.find("fun")print(position)
使用正则表达式从字符串中找出所有匹配的子字符串。示例:
import retext = "my phone numbers are +1-555-1234 and +1-555-5678."numbers = re.findall(r'\+\d{1,3}-\d{3}-\d{4}', text)print(numbers)
使用正则表达式替换字符串中的子字符串。示例:
import retext = "my phone numbers are +1-555-1234 and +1-555-5678."new_text = re.sub(r'\+\d{1,3}-\d{3}-\d{4}', 'xxx-xxx-xxxx', text)print(new_text)
将字符串转换为全小写或全大写。示例:
text = "Hello, World!"lower_text = text.lower()upper_text = text.upper()print(lower_text)print(upper_text)
检查字符串是否以指定的前缀或后缀开头或结尾。示例:
text = "hello, world!"starts_with_hello = text.startswith("hello")ends_with_world = text.endswith("world")print(starts_with_hello)print(ends_with_world)
把一个字符串中的所有单词首字母大写。示例:
import strings = "the quick brown fox jumped over the lazy dog."print(string.capwords(s))
获取字符串的长度。示例:
text = "helloworld"length = len(text)print(length)
格式化文本段落,将文本按照指定宽度进行换行。
为字符串中的所有行增加一致的前缀文本。
编译正则表达式模式,用于后续的匹配操作,可提高效率。示例:
import repattern = re.compile(r'\d+')text = "hello123world"matches = pattern.findall(text)print(matches)
对可迭代对象中的每个元素应用指定的函数,并返回一个新的可迭代对象。示例:
def square(x): return x 2numbers = [1, 2, 3, 4, 5]squared_numbers = map(square, numbers)print(list(squared_numbers))
根据指定的函数过滤可迭代对象中的元素,返回符合条件的元素组成的新可迭代对象。示例:
def is_even(x): return x % 2 == 0numbers = [1, 2, 3, 4, 5, 6]even_numbers = filter(is_even, numbers)print(list(even_numbers))
用于将一个可迭代对象组合为一个索引序列,同时列出元素和其索引。示例:
words = ["apple", "banana", "cherry"]for i, word in enumerate(words): print(f"{i}: {word}")
用于将多个可迭代对象中的元素一一对应地组合成元组,返回一个包含这些元组的可迭代对象。示例:
names = ["Alice", "Bob", "Charlie"]ages = [25, 30, 35]for name, age in zip(names, ages): print(f"{name} is {age} years old.")
将字符串转换为集合,可用于去重以及集合运算。示例:
text = "hello world hello python"word_set = set(text.split())print(word_set)
代码写完了,赶紧试试吧!
更多相关技术内容咨询欢迎前往并持续关注好学星城论坛了解详情。
想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!