import re
def has_mixed_chinese_english(text):
"""
检测字符串是否存在中英文混杂的情况
返回True如果发现以下情况之一:
1. 中文字符串中间包含连续的英文字母(至少2个字母)
2. 英文字符串中间包含中文字符
"""
# 匹配至少2个连续的英文字母或数字
english_pattern = re.compile(r'[a-zA-Z]{2,}')
# 匹配中文字符
chinese_pattern = re.compile(r'[\u4e00-\u9fff]')
# 情况1:中文中夹杂英文
# 找到所有英文片段
for match in english_pattern.finditer(text):
start, end = match.span()
# 检查英文片段前后是否有中文字符
if (start > 0 and chinese_pattern.search(text[start-1])) or \
(end < len(text) and chinese_pattern.search(text[end])):
return True
# 情况2:英文中夹杂中文
if chinese_pattern.search(text):
# 检查中文字符是否出现在英文单词中间
for match in chinese_pattern.finditer(text):
pos = match.start()
# 检查前后是否是英文字母
if (pos > 0 and text[pos-1].isalpha()) and \
(pos < len(text)-1 and text[pos+1].isalpha()):
return True
return False
# 测试用例
test_cases = [
("这是纯中文", False),
("This is pure English", False),
("这是中文with English", True),
("This is 中文 mixed", True),
("Tech技术", True),
("Hello你好World", True),
("中a文", False), # 单个字母不视为混杂
("中ab文", True), # 两个连续字母视为混杂
("a中文b", True),
("123数字", False), # 纯数字不算
("中123文", False) # 数字不算
]
for text, expected in test_cases:
result = has_mixed_chinese_english(text)
print(f"'{text}': {'✅' if result == expected else '❌'} {'混合' if result else '纯净'} (预期: {'混合' if expected else '纯净'})")