TypeError: sequence item 1: expected a bytes-like object, str found
<p>I am trying to extract English titles from a wiki titles dump that's in a text file using regex in Python 3. The wiki dump contains titles in other languages also and some symbols. Below is my code:</p>

<pre><code>with open('/Users/some/directory/title.txt', 'rb')as f:
    text=f.read()
    letters_only = re.sub(b"[^a-zA-Z]", " ", text)
    words = letters_only.lower().split() 
print(words)
</code></pre>

<p>But I am getting an error:</p>

<pre><code>TypeError: sequence item 1: expected a bytes-like object, str found 
</code></pre>

<p>at the line: <code>letters_only = re.sub(b"[^a-zA-Z]", " ", text)</code></p>

<p>But, I am using <code>b''</code> to make output as byte type, below is a sample of the text file:</p>

<pre><code>Destroy-Oh-Boy!!
!!Fuck_you!!
!!Que_Corra_La_Voz!!
!!_(chess)
!!_(disambiguation)
!'O!Kung
!'O!Kung_language
!'O-!khung_language
!337$P34K
!=
!?
!?!
!?Revolution!?
!?_(chess)
!A_Luchar!
!Action_Pact!
!Action_pact!
!Adios_Amigos!
!Alabadle!
!Alarma!
!Alarma!_(album)
!Alarma!_(disambiguation)
!Alarma!_(magazine)
!Alarma!_Records
!Alarma!_magazine
!Alfaro_Vive,_Carajo!
!All-Time_Quarterback!
!All-Time_Quarterback!_(EP)
!All-Time_Quarterback!_(album)
!Alla_tu!
!Amigos!
!Amigos!_(Arrested_Development_episode)
!Arriba!_La_Pachanga
!Ask_a_Mexican!
!Atame!
!Ay,_Carmela!_(film)
!Ay,_caramba!
!BANG!
!Bang!
!Bang!_TV
!Basta_Ya!
!Bastardos!
!Bastardos!_(album)
!Bastardos_en_Vivo!
!Bienvenido,_Mr._Marshall!
!Ciauetistico!
!Ciautistico!
!DOCTYPE
!Dame!_!Dame!_!Dame!
!Decapitacion!
!Dos!
!Explora!_Science_Center_and_Children's_Museum
!F
!Forward,_Russia!
!Forward_Russia!
!Ga!ne_language
!Ga!nge_language
!GÃ£!ne
!GÃ£!ne_language
!GÃ£!nge_language
!HERO
!Happy_Birthday_Guadaloupe!
!Happy_Birthday_Guadalupe!
!Hello_Friends
</code></pre>

<p>I have searched online but could not succeed. Any help will be appreciated.</p>

<p>The problem is with the <code>repl</code> argument you supply, it isn't a <code>bytes</code> object:</p>

<pre><code>letters_only = re.sub(b"[^a-zA-Z]", " ", b'Hello2World')
# TypeError: sequence item 1: expected a bytes-like object, str found
</code></pre>

<p>Instead, supply <code>repl</code> as a bytes instance <code>b" "</code>:</p>

<pre><code>letters_only = re.sub(b"[^a-zA-Z]", b" ", b'Hello2World')
print(letters_only) 
b'Hello World'
</code></pre>

<hr>

<p>Note: Don't prefix your literals with <code>b</code> and don't open the file with <code>rb</code> if you aren't looking for <code>byte</code> sequences. </p>

python regex python-3.x